我想在第一行中显示所有三行,因此我在查询中使用了数据透视 **附上输出图片**
SELECT [Container Number],ReadTimee,Locationn,Trailer FROM
(SELECT [Container Number],ReadTime,Location FROM #temp )as Tab1
PIVOT
(
MAX(ReadTime) FOR Location IN (Trailer,ReadTimee,Locationn)) AS Tab2
我想要这样的输出
ReadTime Location Trailer Container Number ReadTime Location Trailer Container Number ReadTime Location Trailer Container Number
2019-02-27 03:17:21.033 CUSTOM 1 ZIMU1374787,TRHU3437713 2019-02-27 06:10:35.470 ZERO 1 ZIMU1374787,TRHU3437713 2019-02-27 07:30:47.407 CFS 1 ZIMU1374787,TRHU3437713
最佳答案
试试这个:
SELECT Trailer, [Container Number], [CUSTOM] = MAX(CASE WHEN Location = 'CUSTOM' THEN ReadTime ELSE NULL END),
[ZERO] = MAX(CASE WHEN Location = 'ZERO' THEN ReadTime ELSE NULL END),
[CFS] = MAX(CASE WHEN Location = 'CFS' THEN ReadTime ELSE NULL END)
FROM @tmp
GROUP BY Trailer, [Container Number]
以上查询返回:
Trailer Container Number CUSTOM ZERO CFS
1 ZIMU1374787,TRHU3437713 2019-02-27 03:17:21.033 2019-02-27 06:10:35.470 2019-02-27 07:30:47.407
关于sql - 枢轴函数返回空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54922132/