Pivot

如何旋轉多個列

  • August 11, 2016

我有以下數據,

Year        DRC             DISP        Id
0           140.21          0.00        5808
1           112.37          1.00        5808
0           140.21          0.00        5824
1           112.37          0.00        5824

我想像這樣轉動它,

Id          DRC Year 0      DISP Year 0     DRC Year 1      DISP Year 1
5808        140.21          0.00            112.37          1.00
5824        140.21          0.00            112.37          0.00

我試過這個,

SELECT *
FROM
(
   SELECT Year, DRC, DISP, ID From OriginalDataTable
) AS SourceTable

PIVOT
(
   max(DRC)
   for Year IN ([0], [1])
) AS PivotTable;

它以 DRC 為中心,但也不以 DISP 為中心。結果是這樣的(0,1是DRC值)。我明白為什麼會這樣,但是我如何也以 DISP 為中心呢?

DISP        Id          0           1
0.0         5808        140.21      112.37
0.0         5824        140.21      112.37

而不是PIVOT你可以簡單地使用CASE WHEN .... 通過使用GROUP BYthen useMAX(CASE將返回您的預期結果:

使用給定的範例數據執行範例:

DECLARE @OriginalDataTable TABLE (
   [Year] INT, DRC DECIMAL(18,2), DISP DECIMAL(18,2), Id INT);

INSERT INTO @OriginalDataTable ([Year], DRC, DISP, Id) VALUES
(0, 140.21, 0.00, 5808),
(1, 112.37, 1.00, 5808),
(0, 140.21, 0.00, 5824),
(1, 112.37, 0.00, 5824);

SELECT [Id],  
      MAX(CASE WHEN [Year] = 0 THEN DRC END)  AS [DRC Year 0],
      MAX(CASE WHEN [Year] = 0 THEN DISP END) AS [DISP Year 0],
      MAX(CASE WHEN [Year] = 1 THEN DRC END)  AS [DRC Year 1],
      MAX(CASE WHEN [Year] = 1 THEN DISP END) AS [DISP Year 1]
FROM @OriginalDataTable 
GROUP BY [Id]

輸出:

Id      DRC Year 0   DISP Year 0   DRC Year 1   DISP Year 1
5808    140.21       0.00          112.37       1.00
5824    140.21       0.00          112.37       0.00

更多解釋:

SELECT [Id],  
      CASE WHEN [Year] = 0 THEN DRC END   AS [DRC Year 0],
      CASE WHEN [Year] = 0 THEN DISP END  AS [DISP Year 0],
      CASE WHEN [Year] = 1 THEN DRC END   AS [DRC Year 1],
      CASE WHEN [Year] = 1 THEN DISP END  AS [DISP Year 1]
FROM @OriginalDataTable 

上述查詢返回以下結果:

Id      DRC Year 0  DISP Year 0  DRC Year 1  DISP Year 1
5808    140.21      0.00         NULL        NULL
5808    NULL        NULL         112.37      1.00
5824    140.21      0.00         NULL        NULL
5824    NULL        NULL         112.37      0.00

為了避免NULL值和Id明智的結果,我使用了每一列的GROUP BY Idthen MAX(),所以在最終結果中我們可以得到非NULL值作為結果。

引用自:https://dba.stackexchange.com/questions/146336