在sql server

时间:2016-02-16 07:12:30

标签: sql-server

我有两个总和查询

SUM(
    CASE 
        WHEN re.ReApType = 'Allocation' AND re.ReAppType = 'E' AND re.YearID = '2015'
            THEN re.ReCapitalAmount + re.ReRevenueAmount
        ELSE
            0 
    END
) AS RevisedAllocationExcess,
SUM(
    CASE 
        WHEN re.ReApType = 'Allocation' AND re.ReAppType = 'S' AND re.YearID = '2015' 
            THEN re.ReCapitalAmount + re.ReRevenueAmount
        ELSE
            0 
    END
) AS RevisedAllocationSurrender

我想总结这两个问题。请告诉我如何总结它们并在第三栏中显示重新开始。 感谢

3 个答案:

答案 0 :(得分:1)

要获取两列的SUM,请修改CASE表达式:

SUM(
    CASE 
        WHEN re.ReApType = 'Allocation' AND re.ReAppType IN('E','S') AND re.YearID = '2015' 
            THEN re.ReCapitalAmount + re.ReRevenueAmount
        ELSE
            0 
    END
) 

答案 1 :(得分:0)

将该部分代码放入子查询中:

select
  t.RevisedAllocationExcess,
  t.RevisedAllocationSurrender,
  t.RevisedAllocationExcess + t.RevisedAllocationSurrender as RevisedTotal
from
(
  select
    ...
    SUM(...) as RevisedAllocationExcess,
    SIM(...) as RevisedAllocationSurrender
) t

或CTE:

;with cteReviseTotals as
(
  select
    ...
    SUM(...) as RevisedAllocationExcess,
    SIM(...) as RevisedAllocationSurrender
)
select
  t.RevisedAllocationExcess,
  t.RevisedAllocationSurrender,
  t.RevisedAllocationExcess + t.RevisedAllocationSurrender as RevisedTotal
from cteReviseTotals t

答案 2 :(得分:0)

试试这个

SUM(
    CASE 
        WHEN re.ReApType = 'Allocation' AND re.ReAppType = 'E' AND re.YearID = '2015'
            THEN re.ReCapitalAmount + re.ReRevenueAmount
        ELSE
            0 
    END
) AS RevisedAllocationExcess,
SUM(
    CASE 
        WHEN re.ReApType = 'Allocation' AND re.ReAppType = 'S' AND re.YearID = '2015' 
            THEN re.ReCapitalAmount + re.ReRevenueAmount
        ELSE
            0 
    END
) AS RevisedAllocationSurrender,
RevisedAllocationExcess+RevisedAllocationSurrender RevisedSum

希望这会有所帮助......