ID と対応する画像数を含むテーブルがあります。1 で区切られた 200 未満の画像数に基づく ID の数と、100 で区切られた 200 を超える画像数に基づく ID の数を取得したいと考えています。
caseステートメント以外でこれを行う方法はありますか? SQL の For ループのようなものですか?
ループはまったく必要ないと思います。GROUP BY
次の 2 つのクエリで使用および実行できます。
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);
または、次を使用して結果を 1 つの結果セットに結合します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));