考虑一下:
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 |
--------|-------------|----------------------
我被告知这可以使用派生表来实现,但我还没有能够得到它们,只有一个或另一个。
答案 0 :(得分:1)
这可以通过此查询实现(您必须将原始查询作为子查询放在两个位置):
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