旋转行并减去 sql server 2012 中的值

pivot the rows and subtract the values in sql server 2012

我在 sql 服务器中有一个 table 是这样的,

Name    Count1    Count2
------------------------
 AAA     10        15
 BBB     10        NULL
 CCC     NULL      NULL
 DDD     20        10
 EEE     NULL      5

我想使用 pivot 并计算 Count1 和 Count2 之间的差异。

结果应该是这样的,

AAA     BBB    CCC    DDD     EEE
---------------------------------
 -5     10      0     10      -5

让我知道我该怎么做。任何想法都会有所帮助。

谢谢。

Find difference 在数据透视源查询中

SELECT *
FROM   (SELECT name,
               Isnull(Count1, 0) - Isnull(Count2, 0) AS cnt
        FROM   tablename)a
       PIVOT (Max(cnt)
             FOR name IN ([AAA],
                          [BBB],
                          [CCC],
                          [DDD],
                          [EEE]) ) pv 

或使用Conditional Aggregate

SELECT Max(CASE WHEN name = 'AAA' THEN Isnull(Count1, 0) - Isnull(Count2, 0) END) [AAA],
       Max(CASE WHEN name = 'BBB' THEN Isnull(Count1, 0) - Isnull(Count2, 0) END) [BBB],
       Max(CASE WHEN name = 'CCC' THEN Isnull(Count1, 0) - Isnull(Count2, 0) END) [CCC],
       Max(CASE WHEN name = 'DDD' THEN Isnull(Count1, 0) - Isnull(Count2, 0) END) [DDD],
       Max(CASE WHEN name = 'EEE' THEN Isnull(Count1, 0) - Isnull(Count2, 0) END) [EEE]
FROM   tablename

您可以使用 CTE 计算差异,然后对其应用数据透视表:

;WITH CTE AS
 (
    SELECT Name, ISNULL(Count1, 0) - ISNULL(Count2,0) AS Diff
    FROM #T
)
SELECT [AAA], [BBB], [CCC], [DDD], [EEE]
FROM CTE
PIVOT
(
   AVG(Diff)
   FOR Name IN ([AAA], [BBB], [CCC], [DDD], [EEE])
) AS Pvt