gpt4 book ai didi

SQL 数据透视字符串数据

转载 作者:行者123 更新时间:2023-12-01 09:43:43 26 4
gpt4 key购买 nike

我在 SQL Server 中有一个表:Product

产品表:

ImageID  ProductID  
------- ----------
1 P1
1 P2
1 P3
2 S1
2 S2
2 S3
3 M1

这是我需要的输出:

ImageID  Product1ID     Product2ID      Product3ID
----------- ---------- ---------- ----------
1 P1 P2 P3
2 S1 S2 S3
3 M1 null null

一个ImageID最多可以有3个ProductID没有必要所有 ImageID 都有 3 个产品 [例如。图片ID=3]

SELECT ImageID, [Product1ID], [Product2ID], [Product3ID]
FROM
(
SELECT ImageID, ProductID
FROM ProductTable
) AS P
PIVOT
(
max( ImageID)
FOR ProductID IN ([Product1ID], [Product2ID], [Product3ID])
) AS PVT

最佳答案

我只会使用条件聚合:

SELECT ImageID,
MAX(CASE WHEN seqnum = 1 THEN ProductID END) as Product1ID,
MAX(CASE WHEN seqnum = 2 THEN ProductID END) as Product2ID,
MAX(CASE WHEN seqnum = 3 THEN ProductID END) as Product3ID
FROM (SELET pt.*, ROW_NUMBER() OVER (PARTITION BY ImageId ORDER BY ProductID) as seqnum
FROM ProductTable
) P
GROUP BY ImageID;

不过,关键思想是使用 ROW_NUMBER() 来枚举产品。

关于SQL 数据透视字符串数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53764513/

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