[英]SQL Query to sum by month
我有兩個表,“付款表”和“人表”,一個人一個月可以有多個付款,所以我想將一個牧師每月和每年的所有“金額”字段加起來,如果沒有付款,結果應該為0,並且該人的ID應該出現在月份中。
我快到了,但是在我的貨幣查詢中,顯示的數據是每人所有付款,而不是總和。 怎么可能呢?
當前結果是這樣的(請參見10月),我需要對3次付款進行總計,而olny則顯示2013年10月的一行:
我的桌子
MonthNr --- MonthAbr --- ---量---是PersonID YearAmount
1 --- --- JAN 0 --- 2 --- 2013
2 --- --- FEB 0 --- 2 --- 2013
3 --- --- MAR 0 --- 2 --- 2013
4 --- --- APR 0 --- 2 --- 2013
5 --- --- MAY 0 --- 2 --- 2013
6 --- --- JUN 0 --- 2 --- 2013
7 --- --- JUL 0 --- 2 --- 2013
8 --- --- AUG 0 --- 2 --- 2013
9 --- --- SEP 0 --- 2 --- 2013
10 --- --- OCT --- 64,74 2 --- 2013
10 --- --- OCT --- 73,66 2 --- 2013
10 --- --- OCT --- 24.3 --- 2 2013
11 --- --- NOV --- 24.3 --- 2 2013
12 ---- ---- DEC 0 --- 2 ---- 2013
我的查詢:
SELECT
months.monthno as MonthNr,
CAST(CASE WHEN CAST(months.monthno AS int) =1 THEN 'JAN'
WHEN CAST(months.monthno AS int) =2 THEN 'FEB'
WHEN CAST(months.monthno AS int) =3 THEN 'MAR'
WHEN CAST(months.monthno AS int) =4 THEN 'APR'
WHEN CAST(months.monthno AS int) =5 THEN 'MAY'
WHEN CAST(months.monthno AS int) =6 THEN 'JUN'
WHEN CAST(months.monthno AS int) =7 THEN 'JUL'
WHEN CAST(months.monthno AS int) =8 THEN 'AUG'
WHEN CAST(months.monthno AS int) =9 THEN 'SEP'
WHEN CAST(months.monthno AS int) =10 THEN 'OCT'
WHEN CAST(months.monthno AS int) =11 THEN 'NOV'
WHEN CAST(months.monthno AS int) =12 THEN 'DEC'
ELSE
''
END AS nvarchar) as MonthAbr,
Amount = isnull(sum(o.Amount),0),
c.IDPerson as PersonID,
isnull(year(o.Date ),2013) as YearAmount
FROM
Person c
cross join
(select number monthNo from master..spt_values where type='p' and number between 1 and 12) months
full join Payments o
ON o.IDPerson = c.IDPerson
AND month(o.Date ) = months.monthNo
where c.IDPerson = 2
GROUP BY
months.monthno, c.IDPerson ,o.Date
ORDER BY
months.monthno, c.IDPerson
誰能幫我? 提前致謝。
由於您在o.date上使用了isull函數,因此我認為這意味着此列中為null。 如果是這樣,則需要在group by子句中對此進行說明,例如“ group by months.monthno,c.idperson,isull(year(o.date),2013)”。
您不應該按o.Date
,而只能按日期中的月份o.Date
,該日期已包含為months.monthno
。
您為什么不簡化它:
select
months.monthno as MonthNr
,case when monthno='1' then 'JAN'
when monthno='2' then 'FEB'
end as MonthAbr
isnull(year(o.Date ),2013) as YearAmount
,sum(Amount)
from PERSONS c
left join Payments o ON o.IDPerson = c.IDPerson
left join
(select number monthNo from master..spt_values where type='p' and number between 1 and 12) months on months.number= select month(o.Date)
group by months.monthno, o.date
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.