2016-03-03 93 views
0

我有一個包含價格的product_outer表。我想按價格分組,然後數一數。下面的代碼工作的類別「8」中的所有產品:MySQL - 按價格分組 - 計數不同

SELECT price_range, count(*) AS num 
FROM 
(SELECT CASE 

WHEN po.price >= 0 AND po.price < 10 THEN '0.00 - 9.99' 
WHEN po.price >= 10 AND po.price <= 20 THEN '10.00 - 19.99' 
WHEN po.price >= 20 AND po.price <= 30 THEN '20.00 - 29.99' 
WHEN po.price >= 30 AND po.price <= 40 THEN '30.00 - 39.99' 
WHEN po.price >= 40 AND po.price <= 50 THEN '40.00 - 49.99' 
ELSE '50+' 

END as price_range 

FROM product_category pc INNER JOIN product_outer po ON pc.product_outer_id = po.id 
WHERE pc.category_id = '8' AND po.active = '1' 
) AS price_summaries 
GROUP BY price_range 

它提供了以下結果:

price_range  num 
===================== 
10.00 - 19.99  1 
20.00 - 29.99  1 
30.00 - 39.99  1 

我需要進一步採取這一步驟。每個product_outer可以有多個product_inner記錄。我可能需要包括在WHERE子句中product_inner數據,但是當我介紹該表中,計數變爲失控:

SELECT price_range, count(*) AS num 
FROM 
(SELECT CASE 

WHEN po.price >= 0 AND po.price < 10 THEN '0.00 - 9.99' 
WHEN po.price >= 10 AND po.price <= 20 THEN '10.00 - 19.99' 
WHEN po.price >= 20 AND po.price <= 30 THEN '20.00 - 29.99' 
WHEN po.price >= 30 AND po.price <= 40 THEN '30.00 - 39.99' 
WHEN po.price >= 40 AND po.price <= 50 THEN '40.00 - 49.99' 
ELSE '50+' 

END as price_range 

FROM product_category pc INNER JOIN product_outer po ON pc.product_outer_id = po.id INNER JOIN product_inner pi ON pi.product_outer_id = po.id INNER JOIN product_attribute pa ON pa.product_inner_id = pi.id 
WHERE pc.category_id = '8' AND po.active = '1' 
) AS price_summaries 
GROUP BY price_range 

(注FROM線不同)

的輸出如下:

price_range  num 
===================== 
10.00 - 19.99  10 
20.00 - 29.99  6 
30.00 - 39.99  6 

我只想計算不同的po.ID ...我該怎麼做?

回答

1

試試這個:

SELECT price_range, count(distinct id) AS num 
FROM 
(SELECT po.id, CASE 

WHEN po.price >= 0 AND po.price < 10 THEN '0.00 - 9.99' 
WHEN po.price >= 10 AND po.price <= 20 THEN '10.00 - 19.99' 
WHEN po.price >= 20 AND po.price <= 30 THEN '20.00 - 29.99' 
WHEN po.price >= 30 AND po.price <= 40 THEN '30.00 - 39.99' 
WHEN po.price >= 40 AND po.price <= 50 THEN '40.00 - 49.99' 
ELSE '50+' 

END as price_range 

FROM product_category pc INNER JOIN product_outer po ON pc.product_outer_id = po.id INNER JOIN product_inner pi ON pi.product_outer_id = po.id INNER JOIN product_attribute pa ON pa.product_inner_id = pi.id 
WHERE pc.category_id = '8' AND po.active = '1' 
) AS price_summaries 
GROUP BY price_range 
+0

,完美的工作!謝謝! – Lee