对单个列进行求和

时间:2013-11-14 21:27:37

标签: sql tsql

这是我的问题:

select year(p.datetimeentered) as Year, month(p.datetimeentered), datename(month, p.datetimeentered) as Month, st.type as SubType, sum(p.totalpaid) as TotalPaid from master m
inner join jm_subpoena s on s.number = m.number
inner join payhistory p on p.number = m.number
inner join jm_subpoenatypes st on st.id = s.typeid
where p.batchtype in ('PU','PUR','PA','PAR')
and p.datetimeentered > s.completeDate
group by year(p.datetimeentered), month(p.datetimeentered), datename(month, p.datetimeentered), st.type, p.batchtype
order by year(p.datetimeentered), month(p.datetimeentered), datename(month, p.datetimeentered), st.type, p.batchtype

以下是TotalPaid列的条件。

p.batchtypePUPA时,我需要对这些总数求和 当p.batchtypePURPAR时,我需要对这些总数求和 然后我需要从彼此中减去这两个数字。

有一种简单的方法吗?

3 个答案:

答案 0 :(得分:2)

您可以在总和中执行加法/减法:

SUM(CASE 
    WHEN p.batchtype IN ('PU','PA') THEN p.totalpaid 
    WHEN p.batchtype IN ('PUR','PAR') THEN -p.totalpaid 
    ELSE 0 
END) as TotalPaid

答案 1 :(得分:1)

只需使用案例陈述:

Case when p.batch in ('PU','PA') then x + y
else when p.batch in ('PUR, PAR') then x-y
end as YourColumnNameHere

如果我的原始解释不正确,那么pobrelkey的建议就在现场:

sum (
when p.batch in ('PU','PA') then totalpaid
    else when p.batch in ('PUR, PAR') then -totalpaid)
end as YourColumnNameHere

答案 2 :(得分:0)

SELECT Y, M, DATENM, SUBTYPE, (PU_PA_TotalPaid - PUR_PAR_TotalPaid) AS PUMINUSPUR, (PUR_PAR_TotalPaid - PU_PA_TotalPaid) AS PURMINUSPU
FROM
(select year(p.datetimeentered) as Y, month(p.datetimeentered) AS M, datename(month, p.datetimeentered) as DATENM, st.type as SubType, p.batchtype,
SUM(CASE WHEN p.batchtype IN ('PU', 'PA') THEN (p.totalpaid) ELSE 0 END) as PU_PA_TotalPaid ,
SUM(CASE WHEN p.batchtype IN ('PUR', 'PAR') THEN (p.totalpaid) ELSE 0 END) as PUR_PAR_TotalPaid 
from master m
inner join jm_subpoena s on s.number = m.number
inner join payhistory p on p.number = m.number
inner join jm_subpoenatypes st on st.id = s.typeid
where p.batchtype in ('PU','PUR','PA','PAR')
and p.datetimeentered > s.completeDate
group by year(p.datetimeentered), month(p.datetimeentered), datename(month, p.datetimeentered), st.type, p.batchtype
order by year(p.datetimeentered), month(p.datetimeentered), datename(month, p.datetimeentered), st.type, p.batchtype
) A
ORDER BY Y, M, DATENM, SUBTYPE,batchtype