SQL 在数据透视函数中使用 sum(column) 进行查询

SQL query using sum(column) in pivot function

由此

我可以通过代码获取报告:

    SELECT name, 
       [1], 
       [2], 
       [3], 
       [4], 
       [5],
       [6],
       [7],
       [8],
       [9],
       [10],
       [11],
       [12],
       [13],
       [14],
       [15],
       [16],
       [17],
       [18],
       [19], 
       [20], 
       [21], 
       [22], 
       [23], 
       [24], 
       [25], 
       [26], 
       [27], 
       [28], 
       [29], 
       [30], 
       [31],
       ([1] + [2] + [3] + [4] + [5] + [6] + [7] + [8] + [9] + [10] + [11] + [12] + [13] + [14] + [15] + [16] + [17] + [18] + [19] +  [20] + [21] + [22] + [23] + [24] + [25] + [26] + [27] + [28] + [29] + [30] + [31]) as total
FROM   
(
    SELECT Name, 
        id, 
        Datepart(day, [date]) day 
    FROM   item 
    WHERE  MONTH([date]) = 2 AND YEAR([date]) = 2015
) x 
PIVOT 
(
    count(id) 
    FOR day IN ([1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17], [18], [19],  [20], [21], [22], [23], [24], [25], [26], [27], [28], [29], [30], [31]) 
) p

但是现在,我的 table 中有一个新专栏 (amount)(参见 http://imagizer.imageshack.us/a/img911/110/hCx7ho.png

我需要 sum(amount) 来替换 count(id) 以获得按天计算的总金额。

我尝试添加 select 列 amountsum(amount) 来替换 count(id),但它不起作用(我明白了:http://imageshack.com/a/img911/6023/zhMe7I.png

请帮助我或指导我。

count(id) 和 Sum(amount) 都需要吗?如果是,那么您将需要两个数据透视查询。否则你应该能够用这样的数量替换 id:

 .....
FROM   
(
    SELECT Name, 
        amount, 
        Datepart(day, [date]) day 
    FROM   item 
    WHERE  MONTH([date]) = 2 AND YEAR([date]) = 2015
) x 
PIVOT 
(
    sum(amount) 
    FOR day IN ([1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17], [18], [19],  [20], [21], [22], [23], [24], [25], [26], [27], [28], [29], [30], [31]) 
) p