SQL查询按月求和

时间:2013-12-04 13:00:32

标签: sql

我有两个表,付款表和人员表,一个人月可以有多个付款,所以如果没有付款,我希望每月和每年从牧师的所有“金额”字段加起来结果应为0,该人的身份证应出现在月份中。

我几乎在那里,但在我的查询中,显示的数据是每人的所有付款,而不是总和。怎么会这样呢?

目前的结果是这样的(见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
谁能帮助我吗? 提前谢谢。

3 个答案:

答案 0 :(得分:1)

由于您在o.date上使用isnull函数,我认为这意味着此列中存在空值。如果是这样,您需要在group by子句中对此进行说明,例如: “按月分组。月号,c.idperson,isnull(year(o.date),2013)”。

答案 1 :(得分:0)

您不应按o.Date分组,而只能按日期的月份进行分组,该日期已包含在months.monthno中。

答案 2 :(得分:-1)

为什么不简化它:

 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