如何根据sql中同一个表中的另一列设置列的总和值的别名?

时间:2016-02-15 12:16:37

标签: sql sql-server

我有一张Accounts的表格,其中有列:

Acc_IdTransaction_TypeIdAmount

我希望得到的结果为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;

但是这个查询返回了两个不同的结果集。如何在相同的结果集中获取值?

2 个答案:

答案 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