2011-02-08 137 views
0

,我使用MySQL表的排序更具有結構:MySQL查詢結果爲

id | type | date 
-------------------------------- 
    101 |  1  | 2011-02-08 
    102 |  2  | 2011-02-08 
    103 |  2  | 2011-02-08 
    104 |  2  | 2011-02-07 
    105 |  1  | 2011-02-07 
    105 |  1  | 2011-02-07 

我想要做的就是創建一個查詢,將給出以下結果:

total type 1 | total type 2 | date 
------------------------------------------------ 
     1   |  2  | 2011-02-08 
     2   |  1  | 2011-02-07 

我試着用下面的查詢,但沒有得到期望的結果

SELECT count(DISTINCT id) as total, date, type FROM my_table WHERE type !='0' GROUP BY date, type ORDER BY date DESC 

我怎麼能這樣做? 感謝所有建議

回答

1

用途:

SELECT t.date, 
     SUM(CASE WHEN t.type = 1 THEN 1 ELSE 0 END) AS total_type_1, 
     SUM(CASE WHEN t.type = 2 THEN 1 ELSE 0 END) AS total_type_2 
    FROM YOUR_TABLE t 
    WHERE t.type != 0 
GROUP BY t.date 
ORDER BY t.date DESC 

我假設type列基於數字,不串像單引號建議。如果情況並非如此,則更改以適應。

+0

謝謝。這是正確的查詢。 – Sergio 2011-02-08 21:51:24

0

試試這個:

SELECT type, COUNT(*) as total_type, date FROM my_table WHERE type != '0' GROUP BY type ORDER BY date DESC 
0

什麼你問的是透視功能,我的猜測是mysql不是很大。

如果你的作品,我建議改變輸出到:

type count date 
==== ===== ==== 
1  1  2011-02-08 
.... 

,並在應用程序邏輯重新排列。它可能也會讓你的SQL更獨立於數據庫。