2013-04-04 95 views
28

我有以下db表,我希望能夠計算每個銷售人員某些產品的銷售情況。MySQL對特定值的列數進行計算

|------------|------------|------------| 
|id   |user_id  |product_id | 
|------------|------------|------------| 
|1   |1   |2   | 
|2   |1   |4   | 
|3   |1   |2   | 
|4   |2   |1   | 
|------------|------------|------------| 

我希望能夠創建如下的結果集;

|------------|-------------|------------|------------|------------| 
|user_id  |prod_1_count |prod_2_count|prod_3_count|prod_4_count| 
|------------|-------------|------------|------------|------------| 
|1   |0   |2   |0   |1   | 
|2   |1   |0   |0   |0   | 
|------------|-------------|------------|------------|------------| 

我正在使用此數據創建圖表,並且再次(如今天早些時候)我無法計算列總數。我努力了;

SELECT user_id, 
(SELECT count(product_id) FROM sales WHERE product_id = 1) AS prod_1_count, 
(SELECT count(product_id) FROM sales WHERE product_id = 2) AS prod_2_count, 
(SELECT count(product_id) FROM sales WHERE product_id = 3) AS prod_3_count, 
(SELECT count(product_id) FROM sales WHERE product_id = 4) AS prod_4_count 
FROM sales GROUP BY user_id; 

我明白爲什麼這是行不通的,因爲每一個括號中選擇user_ID的不匹配,在主SELECT語句中的外部USER_ID。

任何人都可以幫助我嗎?

感謝您

回答

62

可以使用SUMCASE做到這一點:

select user_id, 
    sum(case when product_id = 1 then 1 else 0 end) as prod_1_count, 
    sum(case when product_id = 2 then 1 else 0 end) as prod_2_count, 
    sum(case when product_id = 3 then 1 else 0 end) as prod_3_count, 
    sum(case when product_id = 4 then 1 else 0 end) as prod_4_count 
from your_table 
group by user_id 
+0

謝謝艾克,這是所有解決方案中最快的解決方案。謝謝:) – 2013-04-04 18:26:47

+2

你不能只是'sum(product_id = 1)'? 'product_id = 1'是一個布爾表達式;它自然會在沒有開關的情況下返回1或0。 – mpen 2015-01-06 19:07:27

+1

@Mark是的,它可以工作得很好,名義上可以更快,但是我發現解決方案寫得更具可讀性。 – 2015-01-06 22:41:35

1

見,如果這個工程:

SELECT a.user_id, 
(SELECT count(b.product_id) FROM sales b WHERE b.product_id = 1 AND a.user_id = b.user_id) AS prod_1_count, 
(SELECT count(b.product_id) FROM sales b WHERE b.product_id = 2 AND a.user_id = b.user_id) AS prod_2_count, 
(SELECT count(b.product_id) FROM sales b WHERE b.product_id = 3 AND a.user_id = b.user_id) AS prod_3_count, 
(SELECT count(b.product_id) FROM sales b WHERE b.product_id = 4 AND a.user_id = b.user_id) AS prod_4_count 
FROM sales a GROUP BY a.user_id; 

乾杯。 n.b.可能會有更好的方法來達到相同的結果。

+2

感謝,這個解決方案沒有工作,但它花了幾秒鐘。艾克的解決方案相比之下非常快,但無論如何感謝您的回答@ d'alar'cop – 2013-04-04 18:28:19

14

您正在嘗試數據。 MySQL不具有旋轉功能,所以你將不得不使用聚合函數與CASE表達:

select user_id, 
    count(case when product_id = 1 then product_id end) as prod_1_count, 
    count(case when product_id = 2 then product_id end) as prod_2_count, 
    count(case when product_id = 3 then product_id end) as prod_3_count, 
    count(case when product_id = 4 then product_id end) as prod_4_count 
from sales 
group by user_id; 

SQL Fiddle with Demo

+1

我希望我能給這1000個向上箭頭。只需點擊旋轉。 – ghukill 2015-03-04 17:49:19