SQL中的透视/非透视

时间:2009-10-19 22:21:03

标签: sql pivot unpivot

我在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行有4V?

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

非常感谢, 彼得

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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