0

これが私のクエリです:

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.batchtypeがあるPU場合は、2 つの数値を互いに減算する必要があります。PAp.batchtypePURPAR

これを行う簡単な方法はありますか?

4

3 に答える 3

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
于 2013-11-14T21:37:11.360 に答える