MySQL - 按价格分组 - 数量不同

时间:2016-03-03 13:22:19

标签: mysql

我有一张包含价格的class TacoListener(tweepy.StreamListener): def on_status(self, status): # Note, I rolled my own Twitter API wrapper, and just had a glance at the Tweepy docs, so some of this syntax might be incorrect, change it as required # I think Tweepy has syntax like: status.text; I'll just refer to the fields as they appear in the Twitter JSON payload for k, v in track.items(): if k in status.get('text') and status.get('screen_name') in v: tweet = "" for name in v: tweet += "@" + name tweet += " are talking about " + k + "! Yum." api.update_status(status=tweet) 表格。我想按价格分组,然后计算。以下代码适用于“8”类别中的所有产品:

product_outer

它给出了以下结果:

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条记录。我可能需要在WHERE子句中包含product_inner数据,但是当我引入此表时,计数会变得混乱:

product_inner

(注意不同的FROM行)

输出如下:

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

我只想计算不同的po.ID ......我怎么能这样做?

1 个答案:

答案 0 :(得分: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