這個查詢將解決您最實際的場景:
SELECT poolmonth,
origination,
[201512],
[201512]+[201601] as [201601],
[201512]+[201601]+[201602] as [201602]
FROM (SELECT poolmonth,
SUM(OriginationAmt) origination,
SUM(CASE WHEN PmtDue = 201512
THEN amtpaid ELSE 0 END) as [201512],
SUM(CASE WHEN PmtDue = 201601
THEN amtpaid ELSE 0 END) as [201601],
SUM(CASE WHEN PmtDue = 201602
THEN amtpaid ELSE 0 END) as [201602]
FROM Loans
GROUP BY poolmonth
) newloans
看到它在這裏工作:http://sqlfiddle.com/#!6/47701/12
這種方法的問題是,如果有更多的幾個月裏,你將不得不手動添加即可。爲了自動執行此操作,您必須創建一個程序來執行此操作,如同在此答案中解釋的那樣:Dynamic SQL PIVOT by @bluefeet
Wocome to SO。偉大的方式來解釋你的問題。但是你也應該在這裏添加這組數據。你的屏幕錄像可能是暫時的,當它死的時候,你的問題將毫無用處。請在這裏添加表格數據和期望的輸出,如果你需要幫助格式化問題。 –