带范围的MySQL查询

时间:2014-02-11 07:36:36

标签: mysql sql

我正在尝试将一组查询简化为一个正在努力解决的问题。

我想收集不同范围的计数,现在正在这样做:

select count(*) from items where value < 0 and id = 43;

select count(*) from items where (value >= 0 AND value <= 10) and id = 43;

select count(*) from items where (value > 10 AND value <= 20) and id = 43;

select count(*) from items where (value > 20 AND value <= 30) and id = 43;

select count(*) from items where value > 30 and id = 43;

我希望能够在单个查询中执行此操作。我怎么能做到这一点?

此外,我仍然需要每个查询计数,而不仅仅是它们的总数。

2 个答案:

答案 0 :(得分:4)

也许是这样的:

SELECT 
    SUM(CASE WHEN value < 0 and id = 43 THEN 1 ELSE 0 END) AS c1
    SUM(CASE WHEN (value >= 0 AND value <= 10) and id = 43 THEN 1 ELSE 0 END) AS c2,
    SUM(CASE WHEN (value > 10 AND value <= 20) and id = 43 THEN 1 ELSE 0 END) AS c3,
    SUM(CASE WHEN (value > 20 AND value <= 30) and id = 43 THEN 1 ELSE 0 END) AS c4,
    SUM(CASE WHEN value > 30 and id = 43 THEN 1 ELSE 0 END) AS c5
FROM 
    items

答案 1 :(得分:4)

SELECT
    SUM( IF(value < 0, 1, 0) ),
    SUM( IF(value BETWEEN 0 AND 10, 1, 0) ),
    SUM( IF(value BETWEEN 10 AND 20, 1, 0) ),
    SUM( IF(value BETWEEN 20 AND 30, 1, 0) ),
    SUM( IF(value > 30, 1, 0) )
FROM items
WHERE id = 43;

试一试