【发布时间】:2013-12-20 23:34:37
【问题描述】:
我有两个表,付款表和人员表,一个人每月可以有多个付款,所以如果没有付款,我想将牧师每月和每年的所有“金额”字段相加结果应为 0,并且此人的 ID 应出现在月份中。
我快到了,但在我的货币查询中,显示的数据是每人的所有付款,而不是总和。怎么办?
目前的结果是这样的(见 10 月),我需要将以下 3 笔付款相加,并且 olny 显示 2013 年 10 月的一行:
我的桌子
MonthNr---MonthAbr---Amount---PersonID---YearAmount
1---JAN---0---2---2013
2---2013年2月---0---2---2013
3---MAR---0---2---2013
4---APR---0---2---2013
5---5月---0---2---2013
6---JUN---0---2---2013
7---七月---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上分组?看起来应该是YearAmount, MonthNr,IDPerson -
当
month(o.Date)在您的连接子句中为空时会发生什么?你为什么不考虑这一点,因为你在这里isnull(year(o.Date ),2013)
标签: sql