计数字段数据透视表在SQL Server中

时间:2015-11-09 14:14:16

标签: sql-server pivot-table

我有这张桌子 - 姓名:Mytable:

         Amount  Desc    Month   Sym  code    ID
        $32,323.00  Bla1    1   121 3   2424221
        $4,242.00   Bla1    1   121 3   2424221
        $3,535.00   Bla1    1   121 1   3230824
        $4,984.00   Bla2    1   433 1   3230824
        $47,984.00  Bla2    2   433 1   3230824
        $41.00      Bla2    2   433 1   3230824
        $3,472.00   Bla6    1   D2  27  2297429
        $3,472.00   Bla6    1   D2  27  2297429
        $3,239.00   Bla6    2   D2  27  2297429
        $4,249.00   Bla8    2   114 24  3434334

ID和月份代表薪水。有6个薪水:1 + 3230824,2 + 3230824等。

我想生成这样一个支点:

       Jan                Feb
     count amount   count amount
121    2    40100$     0    0
433    1    52968$     1   48025$
D2     1    6944$      1   3239$
114    0     0         1   4249$

说明:121是1月份的两个,因为ID = 2424221得到了两次而3230824得到了它一次。薪水中的“事件”数量是两个。

但是,在金额上我总结每一件事来获得该Sym薪水的总金额。

同样,例如,433在2月获得了1的值,因为只有3230824得到它(两次)。

我开始写这个:

SELECT *
FROM (
    SELECT 
        [Sym] as Sym, [Month] as [month], [Amount] as Amount 
    FROM Mytable
) as T
PIVOT
(
    Sum(Amount)
    FOR [Month] IN ([1],[2])
)AS piv

嗯,金额是正确的但是我不知道如何按照我在数据透视表中的金额附近的解释来计算这个数。

1 个答案:

答案 0 :(得分:1)

SELECT
    [Sym],
    COALESCE(SUM(CASE WHEN [1] IS NULL THEN NULL ELSE [Cnt] END), 0) [Jan Count], 
    COALESCE(SUM(CASE WHEN [1] IS NULL THEN NULL ELSE [1] END), 0) [Jan Amount],
    COALESCE(SUM(CASE WHEN [2] IS NULL THEN NULL ELSE [Cnt] END), 0) [Feb Count],
    COALESCE(SUM(CASE WHEN [2] IS NULL THEN NULL ELSE [2] END), 0) [Feb Amount]
FROM (
    SELECT 
        mt1.[Sym] as Sym, mt1.[Month] as [month], mt1.[Amount] as Amount, mt2.[Cnt]
    FROM Mytable mt1
    JOIN (SELECT COUNT(DISTINCT [ID]) [Cnt], [Sym], [Month] 
            FROM MyTable 
            GROUP BY [Sym], [Month]) mt2 
        ON mt1.[Sym] = mt2.[Sym] AND mt1.[Month] = mt2.[Month] 

) as T
PIVOT
(
    Sum(Amount)
    FOR [Month] IN ([1],[2])
)AS piv
GROUP BY [Sym]

SQL Fiddle