SQL数据库中有一张表内容如下
年份     月份      A        B        C       D
2009      1        真      真        假      真
2009      1        假      真        真      真
2009      4        真      真        真      假
                       。
                       。
                       。现在要求对该表按年份、月份进行计数统计得到以下样式的表格
年份     月份      A真  A假   B真   B假    C真    C假    D真   D假
2009      1         1    1     2     0      1      1      2     0
2009      4         1    0     1     0      1      0      0     1
                           。
                           。
                           。单项统计可以通过查询实现,这种多项统计如何用最简单方便的方法实现?  

解决方案 »

  1.   

    to kye_jufei
    我是要对A、B、C、D的真假状态计数统计,而不是显示格式的转换。
      

  2.   

    分两步,先按条件group by,然后行列转换
      

  3.   


    create table e(
      Fyear integer,
      Fmonth smallint,
      a varchar(2),
      b varchar(2),
      c varchar(2),
      d varchar(2)
    );insert into e (Fyear, fmonth, a, b, c, d) values(2009, 1, '真', '真', '假', '真');
    insert into e (Fyear, fmonth, a, b, c, d) values(2009, 1, '假', '真', '真', '真');
    insert into e (Fyear, fmonth, a, b, c, d) values(2009, 4, '真', '真', '真', '假');
    select
      fyear,
      fmonth,
      sum(iif(a = '真', 1, 0)) as "A真",
      sum(iif(a = '假', 1, 0)) as "A假",
      sum(iif(b = '真', 1, 0)) as "B真",
      sum(iif(b = '假', 1, 0)) as "B假",
      sum(iif(c = '真', 1, 0)) as "C真",
      sum(iif(c = '假', 1, 0)) as "C假",
      sum(iif(d = '真', 1, 0)) as "D真",
      sum(iif(d = '假', 1, 0)) as "D假"
    from
      e
    group by fyear, fmonth
      

  4.   

    create table tb(nf varchar(10) , yf varchar(10) , A bit,B bit,C bit,D bit)
    insert into tb values('2009' , '1' ,1,1,0,1)
    insert into tb values('2009' , '1' ,0,1,1,1)
    insert into tb values('2009' , '4' ,1,1,1,0)
     
    goselect * from tb
     
     
     select nf,yf,
     SUM(case when A=1 then A else 0 end) as 'A真',
     SUM(case when A=0 then A else 0 end) as 'A假',
     SUM(case when B=1 then B else 0 end) as 'B真',
     SUM(case when B=0 then B else 0 end) as 'B假',
     SUM(case when C=1 then C else 0 end) as 'C真',
     SUM(case when C=0 then C else 0 end) as 'C假',
     SUM(case when D=1 then D else 0 end) as 'D真',
     SUM(case when D=0 then D else 0 end) as 'D假'
    from tb group by nf,yf/*
    nf         yf         A真          A假          B真          B假          C真          C假          D真          D假
    ---------- ---------- ----------- ----------- ----------- ----------- ----------- ----------- ----------- -----------
    2009       1          1           0           2           0           1           0           2           0
    2009       4          1           0           1           0           1           0           0           0(2 個資料列受到影響)*/
    drop table tb
      

  5.   

    e8923704的执行过程中有错,但我想思路是正确的,
    kye_jufei最后的结果是可以运行的
    谢谢大家
      

  6.   

    http://download.csdn.net/source/1644211