1

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

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

有没有人对表演有任何建议,或者如果这可以通过计数来完成?

4

2 回答 2

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)
于 2013-03-21T16:09:33.290 回答
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;
于 2014-06-17T18:53:15.877 回答