2014-07-24 49 views
-1

我很抱歉,如果這是一個重複的問題,但我找不到我的答案。水平計數SQL

我想獲取水平數據,並獲得特定數字出現次數。

例表

+-------+-------+-------+-------+ 
| Empid | KPI_A | KPI_B | KPI_C | 
+-------+-------+-------+-------+ 
| 232 |  1 |  3 |  3 | 
| 112 |  2 |  3 |  2 | 
| 143 |  3 |  1 |  1 | 
+-------+-------+-------+-------+ 

我需要看到以下內容:

+-------+--------------+--------------+--------------+ 
| EmpID | (1's Scored) | (2's Scored) | (3's Scored) | 
+-------+--------------+--------------+--------------+ 
| 232 |   1 |   0 |   2 | 
| 112 |   0 |   2 |   1 | 
| 143 |   2 |   0 |   1 | 
+-------+--------------+--------------+--------------+   

我希望是有道理的。任何幫助,將不勝感激。

+0

是否肯定**會有**總是**只有三個KPI_x列? – user2338816

回答

1

由於您需要對多列數據進行計數,因此先清除KPI列,然後再計算分數可能會更容易。

您可以使用UNPIVOT函數或CROSS APPLY將您的KPI列轉換爲多行。語法類似於:

select EmpId, KPI, Val 
from yourtable 
cross apply 
(
    select 'A', KPI_A union all 
    select 'B', KPI_B union all 
    select 'C', KPI_C 
) c (KPI, Val) 

請參閱SQL Fiddle with Demo。這麼一來,你的多列到多行,這是那麼容易的工作有:

| EMPID | KPI | VAL | 
|-------|-----|-----| 
| 232 | A | 1 | 
| 232 | B | 3 | 
| 232 | C | 3 | 
| 112 | A | 2 | 

現在您可以輕鬆地數着你已經使用聚合的1的,2的,和3的數量用CASE表達式起作用:

select EmpId, 
    sum(case when val = 1 then 1 else 0 end) Score_1, 
    sum(case when val = 2 then 1 else 0 end) Score_2, 
    sum(case when val = 3 then 1 else 0 end) Score_3 
from 
(
    select EmpId, KPI, Val 
    from yourtable 
    cross apply 
    (
    select 'A', KPI_A union all 
    select 'B', KPI_B union all 
    select 'C', KPI_C 
) c (KPI, Val) 
) d 
group by EmpId; 

參見SQL Fiddle with Demo。這給出了最終結果如下:

| EMPID | SCORE_1 | SCORE_2 | SCORE_3 | 
|-------|---------|---------|---------| 
| 112 |  0 |  2 |  1 | 
| 143 |  2 |  0 |  1 | 
| 232 |  1 |  0 |  2 |