我有一张Accounts
的表格,其中有列:
Acc_Id
,Transaction_TypeId
,Amount
我希望得到的结果为Transaction_TypeId = 1
,然后金额总和为“总预付款”。
否则当Transaction_typeId = 2
然后金额总和为'总接收'
这是我的SQL查询:
SELECT SUM(Amount) AS 'Sum' , Transaction_TypeId INTO #temp1 FROM AccountDetailTable WHERE Account_MasterId = 1 GROUP BY Transaction_TypeId
SELECT Sum as 'Total Advance' from #temp1 WHERE #temp1.Transaction_TypeId = 1;
SELECT Sum as 'Total Cash Receipts' FROM #temp1 WHERE #temp1.Transaction_TypeId = 2;
DROP TABLE #temp1;
但是这个查询返回了两个不同的结果集。如何在相同的结果集中获取值?
答案 0 :(得分:1)
使用CASE
表达式:
SELECT SUM(CASE WHEN Transaction_TypeId = 1 THEN somecolumn END) as [Total Advance],
SUM(CASE WHEN Transaction_TypeId = 2 THEN somecolumn END) as [Total Cash Receipts]
FROM #temp1;
答案 1 :(得分:1)
你应该像这样使用CASE EXPRESSION:
SELECT
sum(case when #temp1.Transaction_TypeId = 1 then amount else 0 end) as 'Total Advance',
sum(case when #temp1.Transaction_TypeId = 2 then amount else 0 end) as 'Total Cash Receipts'
FROM #temp1