2009-10-19 63 views
0

我在SQL中有一個視圖,通過分析表中的值使得該字段包含值'N','D'或'V'。我可以按列計算總數,但不能按行計算......這可能嗎?SQL中的樞軸/未轉位

例子:

數據

No, Col_1, Col_2, Col_3 

1,  N,  N,  N 

2,  N,  D,  D 

3,  N,  V,  D 

4,  V,  V,  V 

如何summise該行3已經1N,1V和3ds而第4行有4Vs?

打賭很簡單,但我很傷心!

很多感謝, 彼得

回答

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; 
+0

除非列的數量是動態的...然後你做一個PIVOT – 2009-10-19 23:06:55

+0

@ d03boy:PIVOT語法只支持SQL Server的2005+和我所知道的的Oracle 11g +上。而恕我直言,CASE語句更容易動態生成。 – 2009-10-20 00:40:24

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