繁体   English   中英

如何在 SQL 中将具有相同 ID 的多行连接成一行?

[英]How would I concatenate many rows with the same ID into a single row in SQL?

这是我的表的当前结构。

在此处输入图片说明

我的目标是像这样设置它:

在此处输入图片说明

我需要做什么查询才能获得此设置?

使用条件聚合:

select
    userId,
    batchId,
    max(case when typeId = 1 then value end) typeId1,
    max(case when typeId = 2 then value end) typeId2,
    max(case when typeId = 3 then value end) typeId3,
    max(case when typeId = 4 then value end) typeId4
from mytable
group by
    userId,
    batchId

你可以旋转。

SELECT userId, batchId, 
[1] AS typeId1,
[2] AS typeId2,
[3] AS typeId3,
[4] AS typeId4
FROM 
(
    SELECT userId, batchId, typeId, [value] 
    FROM yourtable
) src
PIVOT
(
    MAX([value])
    FOR typeId IN ([1],[2],[3],[4])
) pvt
ORDER BY userId, batchId;

在这里测试

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM