我有一张带有 ID 和相应图片计数的表格。我想获得基于图片计数 <200 以 1 分隔的 ID 计数,以及基于图片计数 > 200 以 100 分隔的 ID 计数。
除了case语句,我有什么办法可以做到这一点?SQL中的For循环之类的东西?
我认为你根本不需要任何循环。您可以GROUP BY
在两个查询中使用并执行此操作:
SELECT
FLOOR(pictures / 10) * 10 as `from`,
FLOOR(pictures / 10) * 10 + 9 as `to`,
count(*)
FROM Test
WHERE pictures < 100
GROUP BY FLOOR(pictures / 10);
SELECT
FLOOR(pictures / 100) * 100 as `from`,
FLOOR(pictures / 100) * 100 + 99 as `to`,
count(*)
FROM Test
WHERE pictures >= 100
GROUP BY FLOOR(pictures / 100);
或使用以下方法将结果组合成一个结果集UNION ALL
:
(SELECT
FLOOR(pictures / 10) * 10 as `from`,
FLOOR(pictures / 10) * 10 + 9 as `to`,
count(*)
FROM Test
WHERE pictures < 100
GROUP BY FLOOR(pictures / 10))
UNION ALL
(SELECT
FLOOR(pictures / 100) * 100 as `from`,
FLOOR(pictures / 100) * 100 + 99 as `to`,
count(*)
FROM Test
WHERE pictures >= 100
GROUP BY FLOOR(pictures / 100));