gpt4 book ai didi

sql - 根据字段值对数据进行分类

转载 作者:行者123 更新时间:2023-12-02 07:38:56 25 4
gpt4 key购买 nike

我有一个像这样的表:

userid    cityid
1 4
1 5
2 4
2 1
3 1
3 5

有没有办法在 SQL 或 hive 中将其转换为如下表:

userid    city1    city4   city5
1 false true true
2 true true fase
3 true false true

我不确定有什么词可以形容这种操作...任何帮助将不胜感激!

最佳答案

这基本上是一个PIVOT。您没有指定正在使用的 RDBMS,但您可以使用聚合函数和 CASE 语句在任何数据库中获取结果:

select userid,
max(case when cityid = 1 then 'true' else 'false' end) city1,
max(case when cityid = 2 then 'true' else 'false' end) city2,
max(case when cityid = 3 then 'true' else 'false' end) city3,
max(case when cityid = 4 then 'true' else 'false' end) city4,
max(case when cityid = 5 then 'true' else 'false' end) city5
from yourtable
group by userid

参见 SQL Fiddle with Demo

结果:

| USERID | CITY1 | CITY2 | CITY3 | CITY4 | CITY5 |
--------------------------------------------------
| 1 | false | false | false | true | true |
| 2 | true | false | false | true | false |
| 3 | true | false | false | false | true |

关于sql - 根据字段值对数据进行分类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13309947/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com