2015-10-19 18 views
0

我有以下數據SQL數據透視表結合的多行

+----+-----------+---------+------+------------+-------------+------------+ 
| id | selection | against | runs | firstplace | secondplace | thirdplace | 
+----+-----------+---------+------+------------+-------------+------------+ 
| 1 | a   | a  | 0 |   0 |   0 |   0 | 
| 2 | a   | b  | 20 |   0 |   3 |   0 | 
| 3 | a   | c  | 10 |   0 |   3 |   0 | 
| 4 | a   | d  | 19 |   0 |   3 |   0 | 
| 5 | b   | a  | 20 |   2 |   4 |   1 | 
| 6 | b   | b  | 0 |   0 |   0 |   0 | 
| 7 | b   | c  | 14 |   2 |   4 |   1 | 
| 8 | b   | d  | 23 |   2 |   4 |   1 | 
| 9 | c   | a  | 10 |   0 |   0 |   0 | 
| 10 | c   | b  | 14 |   0 |   0 |   0 | 
| 11 | c   | c  | 0 |   0 |   0 |   0 | 
| 12 | c   | d  | 13 |   0 |   0 |   0 | 
| 13 | d   | a  | 19 |   1 |   2 |   1 | 
| 14 | d   | b  | 23 |   1 |   2 |   1 | 
| 15 | d   | c  | 13 |   1 |   2 |   1 | 
| 16 | d   | d  | 0 |   0 |   0 |   0 | 
+----+-----------+---------+------+------------+-------------+------------+ 

據我瞭解,我需要以返回數據

+---+------------+-------------+------------+------------+ 
| |  a  |  b  |  c  |  d  | 
+---+------------+-------------+------------+------------+ 
| a | 0 [0/0/0] | 20 [0/2/0] | 10 [0/3/0] | 19 [0/3/0] | 
| b | 20 [2/4/1] | 0 [0/0/0] | 14 [2/4/1] | 23 [2/4/1] | 
| c | 10 [0/0/0] | 14 [0/0/0] | 0 [0/0/0] | 13 [0/0/0] | 
| d | 19 [1/2/1] | 23 [13/2/1] | 13 [1/2/1] | 0 [0/0/0] | 
+---+------------+-------------+------------+------------+ 

創建數據透視查詢格式爲運行然後在[]中選擇第一個,第二個和第三個數據,然後根據行選擇列。

我已經查看了所有關於數據透視表的例子,但他們都有計算,只有2或3列。

我是以正確的方式處理數據透視表還是需要查看其他內容?

非常感謝。

回答

0

與戈登更優雅的略有不同。

SELECT selection, 
max(case when against = 'a' then 
    runs + " ["+ firstPlace +"/"+secondPlace+"/"+thirdPlace+"]" end) as "A", 
max(case when against = 'b' then 
    runs + " ["+ firstPlace +"/"+secondPlace+"/"+thirdPlace+"]" end) as "B", 
max(case when against = 'c' then 
    runs + " ["+ firstPlace +"/"+secondPlace+"/"+thirdPlace+"]" end) as "C", 
max(case when against = 'D' then 
    runs + " ["+ firstPlace +"/"+secondPlace+"/"+thirdPlace+"]" end) as "D", 
FROM tableName 
GROUP BY selection 
+0

謝謝,這幫了我很多。 –

1

如果你有四組,那麼你可以編寫查詢做旋轉,或者使用pivot或有條件聚集:

select selection, 
     max(case when against = 'a' then val end) as a, 
     max(case when against = 'b' then val end) as b, 
     max(case when against = 'c' then val end) as c, 
     max(case when against = 'd' then val end) as d 
from (select t.*, 
      replace(replace(replace(replace('@1 [@2/@3/@4]', @1, runs 
              ), @2, firstplace 
            ), @3, secondplace 
          ), @4, thirdplace 
        ) as val 
     from t 
    ) t 
group by selection; 

如果你不知道的組,那麼你需要一個動態的支點。我會建議你谷歌「SQL Server動態數據透視」來獲得解決這個問題的一些方法。