数据库里有这样一个表cards
batchid  status createdate
batchid表示批次,status里1表示停用,2表示正常,createdate表示创建时间现在想输出一个表格,每行显示一个批次的信息,要求查询 '2005-12-12' < createdate < '2010-12-12'时间段中 status = 1的有多少张(count(*)),status = 2的各有多少张
举例为
批号   正常卡     停用卡
34       150         20
35       79          11
......

解决方案 »

  1.   

    select 
        batchid as 批号,
        sum(case status when 2 then 1 else 0 end) as 正常卡,
        sum(case status when 1 then 1 else 0 end) as 停用卡
    from
        cards
    where
        createdate>'2005-12-12' and createdate<'2010-12-12'
    group by
        batchid
      

  2.   

    还想请教一下,还有个cardno字段,我想统计总卡数,cardno为varchar类型,直接用sum(cardno)报错,请问怎么弄?
    我这样写对是对,但感觉怪怪的
    sum(case cardno when 1 then 1 else 1 end) as 总数
      

  3.   

    用count()
    select 
        batchid as 批号,
        sum(case status when 2 then 1 else 0 end) as 正常卡,
        sum(case status when 1 then 1 else 0 end) as 停用卡,
        count(cardno) as 总数
    from
        cards
    where
        createdate>'2005-12-12' and createdate<'2010-12-12'
    group by
        batchid
      

  4.   

    cardno为nvarchar....select 
        batchid as 批号,
        sum(case status when 2 then 1 else 0 end) as 正常卡,
        sum(case status when 1 then 1 else 0 end) as 停用卡,
        count(cast(cardno as int)) as 总数
    from
        cards
    where
        createdate>'2005-12-12' and createdate<'2010-12-12'
    group by
        batchid
      

  5.   

    开玩笑。cardno为nvarchar.... 和count()有关系吗?