按SQL查询的月份老化报告

时间:2014-02-25 20:15:43

标签: sql sql-server sql-server-2008 tsql

从今天起,客户的6个月老化报告。

表格中的数据如下:

    Customer    Date        Amount  
    AAA         3-Sep-13    1000  
    BBB         4-Jan-14    4000  
    BBB         5-Feb-14    1000  
    AAA         3-Dec-13    3000    
    CCC         7-Nov-13    800  
    DDD         15-Nov-13   1000  
    DDD         25-Jan-13   1000  
    CCC         8-Nov-13    1000

我需要一个SQL查询来获得以下结果,标题应该是月份和年份

    Party name  Sep-13  Oct-13  Nov-13  Dec-13  Jan-14  Feb-14  Total Amount  
    AAA         1000      0     0       3000      0      0      4000  
    BBB         0         0     0      4000     1000     0      5000  
    CCC         0         0     1800    0       0        0      1800  
    DDD         0         0     1000    0       1000     0      2000  

1 个答案:

答案 0 :(得分:0)

此查询将动态生成所需的输出。但是,因为您没有所有句点的值,所以插入NULL(有效)。如果要使值0而不是null,则必须修改查询并对每个字段使用ISNULL函数。

CREATE TABLE testTable (
  Party NVARCHAR(20),
  [Date] SMALLDATETIME, --done like this to get a TOTAL heading
  Amount DECIMAL
)

INSERT INTO testTable VALUES 
('AAA','3-Sep-13',1000),
('BBB','4-Jan-14',4000),
('BBB','5-Feb-14',1000),
('AAA','3-Dec-13',3000),
('CCC','7-Nov-13',800),
('DDD','15-Nov-13',1000),
('DDD','25-Jan-13',1000)


INSERT INTO testTable
SELECT Party, '2054-12-31', SUM(Amount) [Amount]
FROM testTable
GROUP BY Party

DECLARE @columnHeadings NVARCHAR(MAX)
SELECT @columnHeadings = COALESCE(
    @columnHeadings + ',[' + CONVERT(NVARCHAR, [Date], 6) + ']',
    '[' + CONVERT(NVARCHAR, [Date], 6)+ ']'
  )
FROM testTable
GROUP BY [Date]
ORDER BY [Date]


DECLARE @sql NVARCHAR(MAX)

SET @sql = N'SELECT [party], ' + @columnHeadings + ' INTO ##output FROM ' +
  '( SELECT [Party], [Amount], CONVERT(NVARCHAR, [Date], 6) [Date] FROM testTable  ) [source]' +
  ' PIVOT ' +
  '( SUM(Amount) FOR [Date] IN (' + @columnHeadings +')) [pvt];'

EXEC(@sql) 

EXEC tempdb.sys.sp_rename '##output.[31 Dec 54]', 'Total', 'COLUMN'

SELECT * FROM ##output

DROP TABLE testTable
DROP TABLE ##output

免责声明:我不喜欢这段代码。但它的确有效。