2016-03-01 64 views
0

我剛剛聲明使用SQL查詢並希望SQL中的某位專家能夠幫助我解決此難題。用於統計行級別重複值的SQL查詢

主表如下

Name Col1 Col2 Col3 Col4 col5 
------------------------------------- 
John T24 T24 T24 T97 J00 
Tom  T24 J01 -  -  - 
James T24 L09 - N78 T97 
John -  -  L56 - T24 

我找SQL查詢語法得到以下兩個結果「結果表1」和「結果表2」

在第一個查詢中,我正在尋找T24或T97在同一行中出現約翰的次數。在第二個查詢中,T24或T97出現在同一個名稱的整列中的次數。我已經展示了作爲結果的表1和表結果2

結果表1

Name T24 T97  Sum of both 
------------------------------------- 
John 3  1  4 
Tom 1  0  1 
James 1  1  2 

成果表2

Name T24 T97  
---------------- 
John 2  0  
Tom 1  0  
James 1  1 

由於下面的示例表爲您的幫助提前。

+0

爲了自己解決問題,你做了什麼? – aribeiro

+0

我不確定過去寫過什麼類型的查詢,因爲我剛開始這項工作。我剛開始使用SQL,並不確定如何獲得此結果。 – Ali

+0

您正在使用哪些DBMS? –

回答

0

試試這個

Select Name 
    , sum(case Col1 when 'T24' then 1 else 0 end) + 
     sum(case Col2 when 'T24' then 1 else 0 end) + 
     sum(case Col2 when 'T24' then 1 else 0 end) + 
     sum(case Col3 when 'T24' then 1 else 0 end) + 
     sum(case Col4 when 'T24' then 1 else 0 end) as T24 
    , sum(case Col1 when 'T97' then 1 else 0 end) + 
     sum(case Col2 when 'T97' then 1 else 0 end) + 
     sum(case Col2 when 'T97' then 1 else 0 end) + 
     sum(case Col3 when 'T97' then 1 else 0 end) + 
     sum(case Col4 when 'T97' then 1 else 0 end) as T97 

    , sum(case Col1 when 'T24' then 1 else 0 end) + 
     sum(case Col2 when 'T24' then 1 else 0 end) + 
     sum(case Col2 when 'T24' then 1 else 0 end) + 
     sum(case Col3 when 'T24' then 1 else 0 end) + 
     sum(case Col4 when 'T24' then 1 else 0 end) + 
     sum(case Col1 when 'T97' then 1 else 0 end) + 
     sum(case Col2 when 'T97' then 1 else 0 end) + 
     sum(case Col2 when 'T97' then 1 else 0 end) + 
     sum(case Col3 when 'T97' then 1 else 0 end) + 
     sum(case Col4 when 'T97' then 1 else 0 end) as SumOfBoth 
from Table 
group by Name 

,並進一步瞭解Case here