0

我通过分析表中的值生成了一个 SQL 视图,以便该字段包含值“N”、“D”或“V”。我可以按列计算总数,但不能按行计算……这可能吗?

例子:

数据

No, Col_1, Col_2, Col_3

 1,     N,     N,     N

 2,     N,     D,     D

 3,     N,     V,     D

 4,     V,     V,     V

我如何总结第 3 行有 1N、1V 和 3ds 而第 4 行有 4Vs?

赌注很简单,但遗憾的是我也是!

非常感谢,彼得

4

2 回答 2

0
 select case when col_1 = 'N' then 1 else 0 end as n_count from tablename;

概括为:

 select 
   case when col_1 = 'N' then 1 else 0 end 
   + case when col_2 = 'N' then 1 else 0 end 
   + case when col_2 = 'N' then 1 else 0 end as n_count,
   case when col_1 = 'V' then 1 else 0 end 
   + case when col_2 = 'V' then 1 else 0 end 
   + case when col_2 = 'V' then 1 else 0 end as v_count,
   ....
  from tablename;
于 2009-10-19T22:28:13.803 回答
0

怎么样?

select no,
sum(case when val = 'N' then 1 else 0 end) ncnt,
sum(case when val = 'V' then 1 else 0 end) vcnt,
sum(case when val = 'D' then 1 else 0 end) dcnt from
(select no, col_1 val from t union all 
 select no, col_2 from t union all
 select no, col_3 from t)
group by no
order by no
于 2009-10-19T22:51:28.177 回答