考虑:
SELECT(count(c.id),
case when(count(c.id) = 0)
then 'loser'
when(count(c.id) BETWEEN 1 AND 4)
then 'almostaloser'
when(count(c.id) >= 5)
then 'notaloser'
end as status,
...
当一切都说完并完成后,查询作为一个整体会产生一组与此类似的结果:
Count | status
--------|-------------
2 | almostaloser //total count is between 2 and 4
--------|-------------
0 | loser // loser because total count = 0
--------|-------------
3 | almostaloser //again, total count between 2 and 4
--------|-------------
我想要实现的目标:
一种重新保留上表中信息的方法,但添加第三列,该列将给出每个状态的总数,类似于
select count(c.id)
case when(count(c.id) = 0 )
then loser as status AND count how many of the total count does this apply to
结果类似于:
Count | status |total_of each status |
--------|-------------|---------------------|
2 | almostaloser| 2 |
--------|-------------|---------------------|
0 | loser | 1 |
--------|-------------|---------------------|
3 | almostaloser| 2 |
--------|-------------|----------------------
我被告知这可以使用派生表来实现,但我还无法同时获得它们,只能获得其中之一。
最佳答案
这可以通过此查询来实现(您必须将原始查询作为子查询放置在两个位置):
SELECT t1.*, t2.total_of_each_status
FROM (
-- put here your query --
) t1
INNER JOIN (
SELECT status, count(*) AS total_of_each_status
FROM (
-- put here your query --
) t2
GROUP BY status
) t2 ON t2.status = t1.status
关于Mysql 使用 case when 语句进行计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26618368/