现在有一个表T1。关键字段5列。查出来的数据如下:(模拟)co1       co2       co3       co4       co5
 1         2         0         1         1
 0         0         1         0         2
 0         1         0         0         1
 1         1         2         1         2
 1         1         2         2         1
 1         1         1         1         1
 0         1         0         1         2
 1         0         1         2         1
 0         0         0         1         2
 1         2         0         1         1
 1         2         0         1         1………………
…………我想要得到5列中 “1”的个数总和,(“1”和“2”)的个数总和,就是这个表里所有的1和2的总和,请问大侠们。SQL要如何写。
在线等……

解决方案 »

  1.   

    SELECT SUM(DECODE(COL1,'1',1,'2',1,0)+DECODE(COL2,'1',1,'2',1,0)+....)
    FROM TABLE1
      

  2.   

    select sum(case when col1 = 1 then 1 else 0 end) + 
           sum(case when col2 = 1 then 1 else 0 end) +
           sum(case when col3 = 1 then 1 else 0 end) +
           sum(case when col4 = 1 then 1 else 0 end) +
           sum(case when col5 = 1 then 1 else 0 end) ,
           sum(case when col1 = 2 then 1 else 0 end) + 
           sum(case when col2 = 2 then 1 else 0 end) +
           sum(case when col3 = 2 then 1 else 0 end) +
           sum(case when col4 = 2 then 1 else 0 end) +
           sum(case when col5 = 2 then 1 else 0 end) 
    from tb