2016-02-07 70 views
7

我對MySQL數據庫這樣的表:是否有可能做出這樣的查詢?

Olimpiade  Sport  Disciplina Categoria 
--------------------------------------------------- 
London 2012 Athletics 100m   men 
London 2012 Athletics 100m   woman 
Beijing 2008 Athletics 200m   men 
Beijing 2008 Athletics 200m   women 
Athens 2004 Athletics 800m   men 
Athens 2004 Athletics 800m   women 

等。 我不知道我是否可以建立這樣的查詢,但我想獲得的結果如下:

Disciplina Categoria London 2012 Beijing 2008 Athens 2004 
------------------------------------------------------------------ 
100m   men   yes   no    yes 
100m   women  yes   yes   no 
200m   men   yes   no    yes 
200m   women  yes   yes   no 
800m   men   yes   yes   yes 
800m   women  yes   yes   yes 

即如果試驗存在或不存在對於奧運版。

+1

屬於[數據透視表](http://www.artfulsoftware.com/infotree/qrytip.php?id=78)的問題。 – 1000111

+2

看看這個[post](http://stackoverflow.com/questions/7674786/mysql-pivot-table)。然後先嚐試一下自己。 – 1000111

回答

3

是的,你可以使用CASE這樣,

Select Disciplina, Categoria, 
CASE when Olimpiade = 'London 2012' then 'yes' else 'no' end as 'London 2012', 
CASE when Olimpiade = 'Beijing 2008' then 'yes' else 'no' end as 'Biejing 2008', 
CASE when Olimpiade = 'Athens 2004' then 'yes' else 'no' end as 'Athens 2004' from tableName group by Disciplina, Categoria order by Disciplina, Categoria 
+1

好的,但這很奇怪,因爲我只在第一次(倫敦2012)和其他人的'不',即使必須得到'是'纔得到'是'。它似乎只適用於第一種情況 – Idro

3

就可以構建一個內部的選擇查詢。內部選擇通過添加列來準備數據。外選擇組數據:

SELECT 
    Disciplina, 
    Categoria, 
    IF (MAX(`London 2012`) > 0, 'yes', 'no') AS 'London 2012', 
    IF (MAX(`Beijing 2008`) > 0, 'yes', 'no') AS 'Beijing 2008', 
    IF (MAX(`Athens 2004`) > 0, 'yes', 'no') AS 'Athens 2004' 
FROM 
    (
     SELECT 
      Disciplina, 
      Categoria, 
      IF (Olimpiade = 'London 2012', 1, 0) AS 'London 2012', 
      IF (Olimpiade = 'Beijing 2008', 1, 0) AS 'Beijing 2008', 
      IF (Olimpiade = 'Athens 2004', 1, 0) AS 'Athens 2004' 
     FROM YourTableName 
    ) AS Games 
GROUP BY Disciplina, Categoria 
ORDER BY Disciplina, Categoria 

你必須與你的表的名稱,以取代YourTableName

+0

是@Henik,謝謝。但尚未糾正。 – datelligence

+1

很棒!這是正確的,謝謝。 – Idro