sql - SQL - 如何将记录的行变成列?
问题描述
我需要一些帮助!!
我的平台中有一个“用户”表。在这张表中,我有如下信息:
id = is the user ID
created_at = is the date that the user created an agreement within the platform
agent = is responsible for serving the user
此信息采用以下格式:
id | created_at | deal_id | agent (columns of the table)
1 | 2020-08-01 | 1 | 123456
1 | 2020-09-01 | 2 | 123456
1 | 2020-09-10 | 3 | 345676
1 | 2020-10-29 | 4 | 456677
我想把这些数据如下:
id | created_at1 | created_at2 | created_at3 | created_at4 | agent1 | agent2 | agent3 | agent4
1 | 2020-08-01 | 2020-09-01 | 2020-09-10 | 2020-10-29 | 123456 | 123456 | 345676 | 456677
可能吗?我试图用最小值和最大值来做,但它只会给我两种情况。记住我给出了一个用户的例子,我希望它返回所有的 ID。
解决方案
您可以按如下方式使用条件聚合:
Select t.id,
Max(case when deal_id = 1 then created_at end) as created_at1,
Max(case when deal_id = 2 then created_at end) as created_at2,
Max(case when deal_id = 3 then created_at end) as created_at3,
Max(case when deal_id = 4 then created_at end) as created_at4,
Max(case when deal_id = 1 then agent end) as agent1,
Max(case when deal_id = 2 then agent end) as agent2,
Max(case when deal_id = 3 then agent end) as agent3,
Max(case when deal_id = 4 then agent end) as agent4
From your_table t
Group by id
推荐阅读
- c++ - 为什么这个简单的 CUDA 内核会得到错误的结果?
- java - 关于变量初始化,构建这组 try catch 块的正确方法是什么?
- google-chrome - Chrome:忽略 --window-size 命令行参数
- javascript - SparkAR javascript toFixed(1) 不起作用
- django - Swagger 没有正确反映 Django Rest Framework 中的 POST 端点定义
- json - 使用通过“Jq”方法检索所需的抵消 json 对象
- javascript - 功能组件:访问共享状态
- c++ - C++ Rookie - 构造函数问题
- angular - 服务数据获取器在 Angular 中返回未定义
- vue.js - 在 vuejs 路由器的 beforeEnter 中等待状态更新