比如 有字段日期 nID(int) WDate(Datetime)
我想按月份分类汇总可以用group by month(WDate)
但是如果当数据没有某月时是没有那个月份的数据的
我期望的效果是
月份  总数
1     5
2     3
3     1
4     0
5     0
.
比如4,5月份是没有数据就为0 
 

解决方案 »

  1.   

    先做一个表,里面生成1到12,然后左连接,后面isnull(总数,0)
      

  2.   


    declare @st datetime  --起始
    declare @et datetime  --结束
    set @st = '2011-05-04'
    set @et = '2011-11-11'
    ;with cte as
    (
        select convert(varchar(7),dateadd(mm,number,@st),120) as yymm
    from master..spt_values
    where [type] = 'p' and number between 0 and datediff(mm,@st,@et)
    )select * from cte/*
    yymm
    -------
    2011-05
    2011-06
    2011-07
    2011-08
    2011-09
    2011-10
    2011-11
    */--可以用cte 去 left join 你查询的表,例如:select a.yymm,sum(b.amount) as amount
    from cte a left join tb b on a.yymm = convert(varchar(7),b.date,120)
    group by a.yymm
      

  3.   


    select A.Number, * from master..spt_values A left join 表 b on A.number=Month(B.日期)
    where A.type='p' and a.number<13
      

  4.   

    select A.Number, * from master..spt_values A left join 表 b on A.number=Month(B.日期)
    where A.type='p' and a.number<13
      

  5.   

    具体怎么做呢?
    像我这样
    select m.MonthName,m.nmonth ,count(*) as total from  Months m  left join sjkaohe s on month(s.kaohedate)=m.nmonth  group by m.MonthName, m.nmonth 
    这样返回
    Month  nMonth   total
    一月 1 120
    二月 2 1
    三月 3 9
    四月 4 9
    五月 5 15
    六月 6 1
    七月 7 1
    八月 8 1
    九月 9 1
    十月 10 1
    十一月 11 1
    十二月 12 23
    这样不对呢?那些为1的应该是0才对!
      

  6.   

    你这里的count(*)有问题,换掉看看
      

  7.   


    declare @t1 table(
    [MonthName] varchar(10),
    [nMonth] tinyint)

    insert into @t1
    select '一月', 1 union 
    select '二月', 2 union
    select '三月', 3
    declare @t2 table(
    [kaohedate] smalldatetime,
    [data] int)insert into @t2
    select '2011-01-02', 1 union
    select '2011-02-01', 2--select * from @t1 order by nMonth
    --select * from @t2select [MonthName], [nMonth], isnull([Total], 0) as [Total] from @t1 as A left join (
    select kaohedate, count(1) as Total from @t2
    group by kaohedate
    ) as B on A.nMonth=MONTH(B.kaohedate)
    order by nMonth
      

  8.   

    (3 行受影响)kaohedate               data
    ----------------------- -----------
    2011-01-02 00:00:00     1
    2011-02-01 00:00:00     2(2 行受影响)MonthName  nMonth Total
    ---------- ------ -----------
    一月         1      1
    二月         2      1
    三月         3      0(3 行受影响)
    表结构不知道,测试的数据,看结果是不是你想要的
      

  9.   


    select m.MonthName,m.nmonth,isnull(s.total,0) from Months m left join 
    (
    select count(1) as total,month(kaohedate) as nMonth  from sjkaohe group by month(kaohedate))s
    on m.nmonth  =s.nMonth楼主依据你的意思应该是这个语句,所以说有时候你自己想的问题所在不是你要求的真正问题所在。所以尽量列出测试数据以及想要的结果,不要考研自己和大家的语文水平