2015-09-29 85 views
0

我有一個名爲'product'的表,其中包含'created_at'日期和'type',它是一個varchar。按類型分組數據並顯示

基本上我想要的是每種產品的COUNT(*)產品的輸出,適用於所有產品類型。我知道「類型」只有5個不同的值,因此可以用我想象的查詢將其縮小一點。

例子:

enter image description here

我一直在玩這個周圍沒有成功,似乎無法總結我的腦海圍繞它。有任何想法嗎?

+0

你只有四種類型? –

+0

是的!我也知道具體的'類型'。 – mdobrenko

+0

'SELECT t1.created_at,count(t1。*),count(t2。*),... FROM product t1 LEFT OUTER JOIN product t2 ON t1.created_at = t2.created_at AND t2.type ='type2'WHERE t1 .type ='type1'GROUP BY t1.created_at' – JimmyB

回答

1

嘗試此查詢

SELECT 
SUM(CASE WHEN type = 'type1' THEN 1 ELSE 0 END) AS type1_count, 
SUM(CASE WHEN type = 'type2' THEN 1 ELSE 0 END) AS type2_count, 
SUM(CASE WHEN type = 'type3' THEN 1 ELSE 0 END) AS type3_count, 
SUM(CASE WHEN type = 'type4' THEN 1 ELSE 0 END) AS type4_count, 
created_at 
GROUP BY created_at 

,對特定日期

SELECT 
SUM(CASE WHEN type = 'type1' THEN 1 ELSE 0 END) AS type1_count, 
SUM(CASE WHEN type = 'type2' THEN 1 ELSE 0 END) AS type2_count, 
SUM(CASE WHEN type = 'type3' THEN 1 ELSE 0 END) AS type3_count, 
SUM(CASE WHEN type = 'type4' THEN 1 ELSE 0 END) AS type4_count, 
created_at 
WHERE created_at = '2015-12-21' 
GROUP BY created_at 

隨着日期格式

SELECT 
SUM(CASE WHEN type = 'type1' THEN 1 ELSE 0 END) AS type1_count, 
SUM(CASE WHEN type = 'type2' THEN 1 ELSE 0 END) AS type2_count, 
SUM(CASE WHEN type = 'type3' THEN 1 ELSE 0 END) AS type3_count, 
SUM(CASE WHEN type = 'type4' THEN 1 ELSE 0 END) AS type4_count, 
DATE_FORMAT(created_at,'%Y/%m/%d') AS created_date 
GROUP BY created_at 
HAVING created_date = '2015/12/21' 
+0

這是否解決了您的問題? –

+0

這工作得很好!忘了問一件事:有沒有辦法將created_at轉換爲日期時間並仍然使用上面的查詢?我試過這個:DATE_FORMAT('created_at',「%Y%m%d」)AS'Date', 然後按'date'分組,但是這給了我一個mysql語法錯誤... – mdobrenko

+0

檢查我編輯的代碼,我已經將日期格式添加到created_at –