我想执行'select count'查询增量值(按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..
如何使其成为有效的单一查询?
答案 0 :(得分: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
请注意,这假设您实际上不想要在边界上重复计算这些值。它不是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