SELECT *
FROM
(SELECT
YEAR (DateOfTransaction) AS year,
LEFT(DATENAME(MONTH, DateOfTransaction), 3) AS month,
SUM(CASE WHEN TransTypeName LIKE 'credit%' THEN amount ELSE 0 END) -
SUM(CASE WHEN TransTypeName LIKE 'Debit%' THEN amount ELSE 0 END) AS Balance
FROM
.............) AS t
PIVOT (SUM(balance) FOR month IN (jan, feb, march, ...., Dec)) AS pvt
此查询返回按月报告的帐户余额。我希望结果是平衡运行。
示例:
1月份我信用5000,2月份我信用2000
我的查询结果是
year jan feb march...dec
2014 5000 2000 null ..null
我想要一个这样的结果:
year jan feb march...dec
2014 5000 7000 null ..null
(5000+2000)
答案 0 :(得分:1)
试试这个
SELECT year,Jan = Jan, Feb = isnull(Jan,0)+isnull(Feb,0),....
FROM
(SELECT
YEAR (DateOfTransaction) AS year,
LEFT(DATENAME(MONTH, DateOfTransaction), 3) AS month,
SUM(CASE WHEN TransTypeName LIKE 'credit%' THEN amount ELSE 0 END) -
SUM(CASE WHEN TransTypeName LIKE 'Debit%' THEN amount ELSE 0 END) AS Balance
FROM
.............) AS t
PIVOT (SUM(balance) FOR month IN (jan, feb, march, ...., Dec)) AS pvt)t
或者您可以简单地添加一个临时表来存储1到12之间的数字
inner join #temp on n>=datepart(mm,DateofTransaction) group by year(transaction), n