MySQL计算一定价格范围之间的列表

时间:2013-03-21 16:04:32

标签: mysql count range between

从网站上的另一篇文章中,我采用了以下类型的查询。他们正在使用总和,我正在寻找列表的数量。

SELECT
COUNT(IF(sold_price < 20,1,0)) as 'Under 20',
COUNT(IF(sold_price BETWEEN 20 and 50,1,0)) as '20 - 50',
COUNT(IF(sold_price BETWEEN 50 and 100,1,0)) as '50 - 100',
COUNT(IF(sold_price BETWEEN 100 and 250,1,0)) as '100 - 250',
COUNT(IF(sold_price BETWEEN 250 and 500,1,0)) as '250 - 500',
COUNT(IF(sold_price BETWEEN 500 and 1000,1,0)) as '500 - 1000',
COUNT(IF(sold_price BETWEEN 1000 and 2000,1,0)) as '1000 - 2000',
COUNT(IF(sold_price > 2000,1,0)) as 'Over 2000'
FROM listings
where current_batch = 'Y'

我的所有结果都以相同的数字返回

Under 20    20 - 50 50 - 100    100 - 250   250 - 500   500 - 1000  1000 - 2000 Over 2000
94665   94665   94665   94665   94665   94665   94665   94665

有没有人在节目中有任何建议可以做到这一点,或者这可以通过计数来完成?

2 个答案:

答案 0 :(得分:3)

MySQL文档说明以下内容(http://dev.mysql.com/doc/refman/5.1/en/group-by-functions.html#function_count):

COUNT(expr) Returns a count of the number of non-NULL values of expr in the rows retrieved by a SELECT statement

所以替换:

IF(sold_price BETWEEN 20 and 50,1,0)

通过

IF(sold_price BETWEEN 20 and 50,1,NULL)

答案 1 :(得分:0)

在查询中使用SUM而不是COUNT,如:

SELECT
SUM(CASE WHEN our_price <= 10000 THEN 1 ELSE 0 END) AS p10000,
SUM(CASE WHEN our_price >= 10001 AND our_price <= 25000 THEN 1 ELSE 0 END) AS p25000,
SUM(CASE WHEN our_price >= 25001 AND our_price <= 50000  THEN 1 ELSE 0 END) AS p50000,
SUM(CASE WHEN our_price >= 50001 AND our_price <= 75000  THEN 1 ELSE 0 END) AS p75000,
SUM(CASE WHEN our_price >= 75001 AND our_price <= 100000  THEN 1 ELSE 0 END) AS p100000,
SUM(CASE WHEN our_price >= 100001 AND our_price <= 150000  THEN 1 ELSE 0 END) AS p150000,
SUM(CASE WHEN our_price >= 151000 AND our_price <= 200000  THEN 1 ELSE 0 END) AS p200000,
SUM(CASE WHEN our_price > 200000 THEN 1 ELSE 0 END) AS p200001
FROM products;