SQL

本帖最后由 lisetlo 于 2010-12-14 09:28:41 编辑

解决方案 »

  1.   

    select sum(case when [type]='上午' then 1 else 0 end )上午,
           sum(case when [type]='中午' then 1 else 0 end )中午,
           sum(case when [type]='下午' then 1 else 0 end )下午,
           sum(case when [type]='晚上' then 1 else 0 end )晚上
    from tb
      

  2.   

    --建表
    if object_id('t1')is not null
       drop table t1
    go
    create table t1(
    id int identity,
    type char(4) check (type in('上午','中午','下午','晚上')),
    time datetime
    )
    --插入数据
    insert into t1 
    select '上午','2010-12-10 08:20:00' union all
    select '上午','2010-12-10 11:15:00' union all
    select '中午','2010-12-10 12:30:00' union all
    select '下午','2010-12-10 15:00:00' union all
    select '下午','2010-12-10 17:00:00' union all
    select '晚上','2010-12-10 19:00:00' union all
    select '晚上','2010-12-10 22:30:00'
    --测试
    select type ,count(*) '总记录数' from t1 group by type  
    type 总记录数
    上午 2
    晚上 2
    下午 2
    中午 1
      

  3.   

    用case when分支语句实现即可:select sum(case when [type]='上午' then 1 else 0 end ) as 上午,
           sum(case when [type]='中午' then 1 else 0 end ) as 中午,
           sum(case when [type]='下午' then 1 else 0 end ) as 下午,
           sum(case when [type]='晚上' then 1 else 0 end ) as 晚上
    from 表名
      

  4.   


    drop table tbcreate table tb(
    id int identity,
    type char(4) check (type in('sw','zw','xw','ws')),
    time int
    )
    --插入数据
    insert into tb values ('sw',1) 
    insert into tb values ('sw',2 )
    insert into tb values ('zw',1)
    insert into tb values ('zw',1)
    insert into tb values ('zw',1)
    insert into tb values ('xw',2 )
    insert into tb values ('xw',3)
    insert into tb values ('ws',3) 
    insert into tb values ('ws',4)
    select * from tb
    select sum(case when [type]='sw' then 1 else 0 end ) as morning, 
           cast( sum(case when [type]='sw' then time else 0 end ) as varchar)+' hours' as morningTimeSum ,
           sum(case when [type]='zw' then 1 else 0 end ) as noon, 
           cast(sum(case when [type]='zw' then time else 0 end )as varchar)+' hours'  as NoonTimeSum ,
           sum(case when [type]='xw' then 1 else 0 end ) as afternoon, 
           cast(sum(case when [type]='xw' then time else 0 end )as varchar) +' hours' as afternoonTimeSum ,
           sum(case when [type]='ws' then 1 else 0 end ) as night, 
           cast(sum(case when [type]='ws' then time else 0 end )as varchar) +' hours' as nightTimeSum 
    from tb