PIVOT Query提供NULL值

时间:2015-07-29 10:17:54

标签: sql-server sql-server-2008 sql-server-2008-r2 sql-server-2012 pivot

我的实际表格如下:

   DATE       Server           DURATION_
2015-04-01    BANGLR           01:11:00.0000000
2015-04-01    ERRAMANJIL       00:19:00.0000000
2015-04-01    THANE            00:42:00.0000000
2015-04-02    BANGLR           01:27:00.0000000
2015-04-02    ERRAMANJIL       00:20:00.0000000
2015-04-02    THANE            00:33:00.0000000

我正在使用以下PIVOT查询:

SELECT DATE, BANGLR, THANE, ERRAMANJIL FROM abrlmis_hmdmtracking
PIVOT (MAX(DURATION_) for [Server] IN (BANGLR,THANE,ERRAMANJIL)) AS [SERVER]
WHERE [DATE] IS NOT NULL 
GROUP BY DATE, BANGLR,THANE,ERRAMANJIL

但它给出的结果为空值,如下所示:

   DATE      BANGLR              THANE                   ERRAMANJIL
2015-04-01   01:11:00.0000000    NULL                    NULL
2015-04-01   NULL                NULL                    NULL
2015-04-01   NULL                NULL                    00:19:00.0000000
2015-04-01   NULL                00:42:00.0000000        NULL
2015-04-02   01:27:00.0000000    NULL                    NULL
2015-04-02   NULL                NULL                    NULL
2015-04-02   NULL                NULL                    00:20:00.0000000
2015-04-02   NULL                00:33:00.0000000        NULL

但我想要的结果是这样的:

   DATE      BANGLR             THANE              ERRAMANJIL
2015-04-01   01:11:00.0000000   00:42:00.0000000   00:19:00.0000000
2015-04-02   01:27:00.0000000   00:33:00.0000000   00:20:00.0000000

如何实现这一目标?

1 个答案:

答案 0 :(得分:3)

从下面的T-SQL语句中可以看到,您的查询可以正常使用提供的数据:

DECLARE @DataSource TABLE
(
    [DATE] DATE
   ,[Server] VARCHAR(12)
   ,[DURATION_] VARCHAR(18)
);

INSERT INTO @DataSource ([DATE], [Server], [DURATION_])
VALUES ('2015-04-01', 'BANGLR', '01:11:00.0000000')
      ,('2015-04-01', 'ERRAMANJIL', '00:19:00.0000000')
      ,('2015-04-01', 'THANE', ' 00:42:00.0000000')
      ,('2015-04-02', 'BANGLR', '01:27:00.0000000')
      ,('2015-04-02', 'ERRAMANJIL', '00:20:00.0000000')
      ,('2015-04-02', 'THANE', '00:33:00.0000000');

SELECT TOP 8 DATE, BANGLR, THANE, ERRAMANJIL 
FROM @DataSource
PIVOT 
(
    MAX(DURATION_) FOR [Server] IN (BANGLR,THANE,ERRAMANJIL)
) AS [SERVER]
WHERE [DATE] IS NOT NULL 
GROUP BY DATE, BANGLR,THANE,ERRAMANJIL;

enter image description here

所以,我相信你提取的更多列已经向我们展示了(其中一些是独一无二的)。要解决这个问题,您可以这样做:

SELECT TOP 8 DATE, BANGLR, THANE, ERRAMANJIL 
FROM 
(
    SELECT [DATE] 
          ,DURATION_
          ,[Server]
    FROM @DataSource
    WHERE [DATE] IS NOT NULL 
) DS
PIVOT 
(
    MAX(DURATION_) FOR [Server] IN (BANGLR,THANE,ERRAMANJIL)
) AS [SERVER];