具体的我也说不清,还是举点列子更直观一些。
如下表
营业店  金额 日期  
001    10   2011.01
001    15   2011.01
001    20   2011.02
002    10   2011.01
002    30   2011.02
现在我要从上表得到后如下的形式显示
营业店  件数和 金额和  一月份件数 一月份金额和   二月份件数 二月份金额和
001      3     45     2            25         1          20  
002      2     40     1            10         1          30
怎么取得分组后每个组每个月份的合计值 就不太清楚了,望指教!

解决方案 »

  1.   

    sum(case when .. then ..) 
      

  2.   

    select
       营业店,
       count(1) as 件数和,
       sum(金额) as 金额和,
       sum(case when datepart(mm,日期)=1 then 1 else 0 end) as 一月份件数,
       sum(case when datepart(mm,日期)=1 then 金额 else 0 end) as 一月金额和,
       sum(case when datepart(mm,日期)=2 then 1 else 0 end) as 二月份件数,
       sum(case when datepart(mm,日期)=2 then 金额 else 0 end) as 二月金额和
    from
      tb
    group by
       营业店
      

  3.   

    select 营业店,count(*) as 件数和,sum(金额) as 金额和,
       sum(case when datepart(mm,日期)=1 then 1 else 0 end) as [一月份件数],
       sum(case when datepart(mm,日期)=1 then 金额 else 0 end) as [一月金额和],
       sum(case when datepart(mm,日期)=2 then 1 else 0 end) as [二月份件数],
       sum(case when datepart(mm,日期)=2 then 金额 else 0 end) as [二月金额和]
    from tb group by 营业店
      

  4.   

    select
       营业店,
       count(1) as 件数和,
       sum(金额) as 金额和,
       sum(case when datepart(mm,日期)=1 then 1 else 0 end) as 一月份件数,
       sum(case when datepart(mm,日期)=1 then 金额 else 0 end) as 一月金额和,
       sum(case when datepart(mm,日期)=2 then 1 else 0 end) as 二月份件数,
       sum(case when datepart(mm,日期)=2 then 金额 else 0 end) as 二月金额和
    from
      tb
    where
       convert(varchar(7),日期,120) between '2011-01' and '2011-08'
    group by
       营业店
      

  5.   

    create table tb(营业店 varchar(10),金额 int,日期 varchar(10))
    insert into tb select '001',10,'2011.01'
    insert into tb select '001',15,'2011.01'
    insert into tb select '001',20,'2011.02'
    insert into tb select '002',10,'2011.01'
    insert into tb select '002',30,'2011.02'
    insert into tb select '001',50,'2011.08'
    insert into tb select '002',100,'2011.08'
    go
    declare @s nvarchar(4000)
    select @s=isnull(@s+',','')+'['+ 日期 +']' from(
    select distinct 日期 from tb
    )t
    exec('select 营业店,'+@s+'from tb pivot (sum([金额]) for [日期] in('+@s+'))b')
    /*
    营业店        2011.01     2011.02     2011.08
    ---------- ----------- ----------- -----------
    001        25          20          50
    002        10          30          100(2 行受影响)
    */
    go
    drop table tb
      

  6.   

    当然非要动态的话:declare @sql varchar(8000)
    set @sql = 'select 营业店 '
    select @sql = @sql + ' , 
    sum(case  datepart(mm,日期) when ''' + datepart(mm,日期) + ''' then 1 else 0 end) [' +  datepart(mm,日期) + '月份件数],
    sum(case  datepart(mm,日期) when ''' + datepart(mm,日期) + ''' then 金额 else 0 end) [' +  datepart(mm,日期) + '月金额和],
    '
    from (select distinct datepart(mm,日期) from tb) as a
    set @sql = @sql + ' from tb group by 营业店'
    exec(@sql)