sql - 枢轴函数返回空值

标签 sql sql-server sql-server-2012

我想在第一行中显示所有三行,因此我在查询中使用了数据透视 **附上输出图片** enter image description here

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  

但是使用上面的查询返回 null .输出图片如下所示 enter image description here

我想要这样的输出

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/

相关文章:

java - 如何基于 2 个键创建 JDBC upsert 查询

sql - 每周总计唯一序列号

java - 在java callablestatement中设置uniqueidentifier

sql-server - SQL Server 2012 中关于在 ISNULL() 中进行转换的新增功能

sql - 如何在作为变量传递的表名上设置identity_insert

SQL Server : convert string with format dddd mm/dd/yy to date

java - 在所有列上解析 Array_agg

php - 查询以在表中的间隔内计数

sql - SQL Server 中的 SUBQUERY 和 EXISTS

php - MySQL 查询 - 间隔求和