有一个表如下:
日期   编号
9.24    2
9.24    2
9.25    1
9.26    3
9.27    1
要求查询的结果是:就是统计个数
日期   编号1  编号2  编号3
9.24          2      
9.25   1      
9.26                  1
9.27   1
那么这个SQL语句怎么写呢?多谢了。。

解决方案 »

  1.   

    select 日期,sum(case when 编号=1 then 1 else 0 end) 编号1,sum(case when 编号=2 then 1 else 0 end) 编号2,sum(case when 编号=3 then 1 else 0 end) 编号3
    from 表 group by 日期
      

  2.   

    那是可以的,如果我的编号有20项,那么也要一项项的写吗?也就是case 里面不要直接用
    ‘编号=1’这些,
      

  3.   

    我是在SQL2000中写的,能不能写成循环的格式嘛,请高手指教。。
      

  4.   

    这是交叉表的一种形式,可以写成存储过程,动态生成sql语句,不过要保证语句不超过8000字符根据编号的项目,用游标循环各编号,生成相应的sql语句
    再通过执行exec执行所生成的语句返回结果
      

  5.   

    --简单写了一个,你根据自己实际的情况做调整了create table test
    ([id] int identity not null,
    日期 datetime NULL,
    编号 int NULL
    )insert into test values(convert(varchar(10),getdate()-4,120),2)
    insert into test values(convert(varchar(10),getdate()-4,120),2)
    insert into test values(convert(varchar(10),getdate()-3,120),1)
    insert into test values(convert(varchar(10),getdate()-2,120),3)
    insert into test values(convert(varchar(10),getdate()-1,120),1)select * from testdeclare @code int
    declare @sql varchar(8000)
    set @sql=''declare aaa cursor
    for select 编号 from test group by 编号
    open aaa
    fetch next from aaa into @code
    while @@fetch_status = 0 
    begin
    set @sql=@sql+',sum(case when 编号='+convert(varchar,@code)+' then 1 else 0 end) as 编号'+convert(varchar,@code)
    fetch next from aaa into @code
    end
    close aaa
    deallocate aaaset @sql='select 日期'+@sql+' from test group by 日期'
    exec(@sql)drop table test