2012-09-29 72 views
3

這是我的MySQL表的快照:MySQL的支點與多個計數

enter image description here

是否可以編寫一個查詢得到像這樣的輸出數據透視表...

enter image description here

+2

能不能讓您的記錄,而不是屏幕截圖的文本格式? –

回答

2

您可以使用CASE聲明來調整您的表。

SELECT url_host, 
     COUNT(CASE WHEN post_ID = -1 THEN 1 ELSE NULL END) Negative_One, 
     COUNT(CASE WHEN post_ID = 0 THEN 1 ELSE NULL END) Zero, 
     COUNT(CASE WHEN post_ID > 0 THEN 1 ELSE NULL END) Greater_Zero 
FROM tableName 
GROUP BY url_host 

SQLFiddle Demo

+0

COUNT會計數1和0 ... –

+0

downvoted?沒關係.. –

+1

把它交給@astander,因爲這是第一個答覆。多謝你們! –

3

如何像

SELECT url_host, 
    SUM(CASE WHEN post_id = -1 THEN 1 ELSE 0 END) as post_id_minus1, 
    SUM(CASE WHEN post_id = 0 THEN 1 ELSE 0 END) as post_id_0, 
    etc... 
FROM YOUR_TABLE 
GROUP BY url_host