我在这个项目工作上这么晚。
我觉得我是家乡。我有两个表pay
和chg
。尝试先做老化桶,然后我想减去相关的桶(chg
(chg
0-30) - pmt
(pmt
0-30))Am我走在正确的轨道上。
SELECT fgc, sum(pay) from
(SELECT fgc, pay,
CASE
WHEN [date]<= 30 THEN 'pmt 0-30'
WHEN [date]> 30 AND [date] <= 60 THEN 'pmt 30-60'
WHEN [date]> 61 AND [date] <= 90 THEN 'pmt 61-90'
WHEN [date]> 91 AND [date] <= 120 THEN 'pmt 91-120'
WHEN [date]> 121 AND [date] <= 150 THEN 'pmt 121-150'
WHEN [date]> 151 AND [date] <= 180 THEN 'pmt 151-180'
ELSE 'pmt 181+'
END)
FROM @pay(fgc,pay,[date])
SELECT fgc, sum(chg) from
(SELECT fgc, chg,
CASE
WHEN [date]<= 30 THEN 'pmt 0-30'
WHEN [date]> 30 AND [date] <= 60 THEN 'charge 30-60'
WHEN [date]> 61 AND [date] <= 90 THEN 'charge 61-90'
WHEN [date]> 91 AND [date] <= 120 THEN 'charge 91-120'
WHEN [date]> 121 AND [date] <= 150 THEN 'charge 121-150'
WHEN [date]> 151 AND [date] <= 180 THEN 'charge 151-180'
ELSE 'pmt 181+'
END)
FROM @chg (fgc,chg,[date])
GROUP by fgc
答案 0 :(得分:1)
这应该让你开始:
select fgc,sum(Totpay) as TotPay,Sum(TotChg) as TotChg
from
(
SELECT fgc, sum(pay) as TotPay,0 as TotChg
from
(SELECT fgc, pay,
CASE
WHEN [date]<= 30 THEN 'pmt 0-30'
WHEN [date]> 30 AND [date] <= 60 THEN 'pmt 30-60'
WHEN [date]> 61 AND [date] <= 90 THEN 'pmt 61-90'
WHEN [date]> 91 AND [date] <= 120 THEN 'pmt 91-120'
WHEN [date]> 121 AND [date] <= 150 THEN 'pmt 121-150'
WHEN [date]> 151 AND [date] <= 180 THEN 'pmt 151-180'
ELSE 'pmt 181+'
END)
FROM @pay
GROUP by fgc
UNION
SELECT fgc, 0 as TotPay,sum(chg) as TotChg
from
(SELECT fgc, chg,
CASE
WHEN [date]<= 30 THEN 'pmt 0-30'
WHEN [date]> 30 AND [date] <= 60 THEN 'charge 30-60'
WHEN [date]> 61 AND [date] <= 90 THEN 'charge 61-90'
WHEN [date]> 91 AND [date] <= 120 THEN 'charge 91-120'
WHEN [date]> 121 AND [date] <= 150 THEN 'charge 121-150'
WHEN [date]> 151 AND [date] <= 180 THEN 'charge 151-180'
ELSE 'pmt 181+'
END)
FROM @chg
GROUP by fgc
) xx
GROUP BY fgc