我有一个从数据库返回计数的查询。查询的示例输出:
23
14
94
42
23
12
查询:
SELECT COUNT(*)
FROM `submissions`
INNER JOIN `events`
ON `submissions`.event_id = `events`.id
WHERE events.user_id IN (
SELECT id
FROM `users`
WHERE users.created_at IS NOT NULL
GROUP BY `events`.id
有没有办法轻松获取输出并将其拆分为预定义的值范围(0-100,101-200等),表明属于特定范围的行数?
答案 0 :(得分:1)
在select子句中使用case表达式。
SELECT `events`.id ,
case when COUNT(`events`.id) between 0 and 100 then '0 - 100'
when COUNT(`events`.id) between 100 and 200 then '100 - 200'
end as Range
FROM `submissions`
INNER JOIN `events`
ON `submissions`.event_id = `events`.id
WHERE events.user_id IN (
SELECT id
FROM `users`
WHERE users.created_at IS NOT NULL
GROUP BY `events`.id
答案 1 :(得分:1)
通过利用SUM()
聚合来使用条件计数。
如果您需要列中的范围
SELECT SUM(CASE WHEN n BETWEEN( 0 AND 100) THEN 1 ELSE 0 END) '0-100',
SUM(CASE WHEN n BETWEEN(101 AND 200) THEN 1 ELSE 0 END) '101-200'
-- , add other ranges here
FROM (
SELECT COUNT(*) n
FROM submissions s JOIN events e
ON s.event_id = e.id JOIN users u
ON e.user_id = u.id
WHERE u.created_at IS NOT NULL
GROUP BY e.id
) q
示例输出
+-------+---------+ | 0-100 | 101-200 | +-------+---------+ | 2 | 3 | +-------+---------+ 1 row in set (0.01 sec)
如果你想把它作为一套你可以做到
SELECT CONCAT(r.min, '-', r.max) `range`,
SUM(n BETWEEN r.min AND r.max) count
FROM (
SELECT COUNT(*) n
FROM submissions s JOIN events e
ON s.event_id = e.id JOIN users u
ON e.user_id = u.id
WHERE u.created_at IS NOT NULL
GROUP BY e.id
) q CROSS JOIN (
SELECT 0 min, 100 max
UNION ALL
SELECT 101, 200
-- add other ranges here
) r
GROUP BY r.min, r.max
示例输出
+---------+-------+ | range | count | +---------+-------+ | 0-100 | 2 | | 101-200 | 3 | +---------+-------+ 2 rows in set (0.01 sec)