0

我想执行“选择计数”查询增量值(5)

像这些 sql 查询:

SELECT COUNT(*) FROM ages WHERE ages.year BETWEEN 1990 and 1995
SELECT COUNT(*) FROM ages WHERE ages.year BETWEEN 1995 and 2000
..so fort and so on..

我怎样才能使它成为一个有效的单一查询?

4

1 回答 1

0
SELECT COUNT(*) AS `count`, (ages.year DIV 5) * 5 AS bottom, 
    (ages.year DIV 5 + 1) * 5 AS top
FROM ages
GROUP BY (ages.year DIV 5) * 5, (ages.year DIV 5 + 1) * 5

SQL 小提琴示例

请注意,这假设您实际上不想在边界上重复计算这些值。它不是 100% 完全像您的原始查询。如果您确实想重复计算,请尝试:

SELECT SUM(`count`) AS `count`, bottom, top
FROM
(
    SELECT COUNT(*) AS `count`, (ages.year DIV 5) * 5 AS bottom, 
        (ages.year DIV 5 + 1) * 5 AS top
    FROM ages
    GROUP BY (ages.year DIV 5) * 5, (ages.year DIV 5 + 1) * 5
    UNION ALL
    SELECT 1 AS `count`, ages.year - 5 AS bottom, ages.year AS top
    FROM ages
    WHERE MOD(ages.year, 5) = 0
) inclusive
GROUP BY bottom, top

SQL 小提琴示例

于 2013-01-26T11:22:23.510 回答