MySQL查询将数据分组到不同的范围

时间:2015-05-19 20:09:10

标签: mysql

我在这里找到了解决方案, sql query that groups different items into buckets

只要有所有范围的数据,它就能正常工作。如果没有数据,我希望查询返回0.

所以,如果我的表是:

item_name | price
i1        | 2
i2        | 22
i3        | 4
i4        | 26
i5        | 44
i6        | 6

我希望输出为:

range   | number of item
0 - 10  |  3
11 - 20 |  0
21 - 30 |  2
31 - 40 |  0
41 - 50 |  1

以下查询不会显示0计数案例的结果。

select
      case when price >= 0 and price <= 10    then "  0 - 10"
           when price > 10 and price <= 20   then " 10 - 20"
           when price > 20 and price <= 30   then " 20 - 30"
           when price > 30 and price <= 40  then " 30 - 40"
           when price > 40 and price <= 50  then " 40 - 50"
           else "over 50"
      end PriceRange,
      count(*) as TotalWithinRange
   from
      YourTable
   group by 1

有人有解决方案吗?

3 个答案:

答案 0 :(得分:1)

您需要构建一个包含所有价格范围的内联表。然后根据您的查询对派生表执行LEFT JOIN以获得预期结果:

SELECT x.PriceRange, COALESCE(TotalWithinRange, 0) AS TotalWithinRange
FROM (
  SELECT "0 - 10" AS PriceRange 
  UNION SELECT "10 - 20"
  UNION SELECT "20 - 30"
  UNION SELECT "30 - 40"
  UNION SELECT "40 - 50"
  UNION SELECT "over 50" ) x
LEFT JOIN (  
   SELECT
      CASE when price >= 0 and price <= 10 then "0 - 10"
           when price > 10 and price <= 20 then "10 - 20"
           when price > 20 and price <= 30 then "20 - 30"
           when price > 30 and price <= 40 then "30 - 40"
           when price > 40 and price <= 50 then "40 - 50"
           else "over 50"
      END AS PriceRange,
      COUNT(*) as TotalWithinRange
   FROM YourTable
   GROUP BY 1 ) y ON x.PriceRange = y.PriceRange

SQL Fiddle Demo

答案 1 :(得分:0)

TotalWithinRange分组,因此它会计算每个类别

答案 2 :(得分:0)

这可能不是最有效的答案,但您可以为每个组尝试单独的SUM(CASE)语句。例如:

SUM(CASE WHEN price >= 0 AND price <= 10 THEN 1 ELSE 0 END) AS "0-10"

等等。这应该打印出SUMs为0的类别。