我不擅长SQL,我有一个非常特殊的要求。
我的表看起来像这样:
FOO BAR
----+----
foo1 bar1
foo2 bar3
foo1 bar1
foo1 bar1
foo2 bar3
foo4 bar3
foo3 bar2
foo2 bar4
foo5 bar4
我可以轻松管理每个不同“条形”条目的数量
SELECT bar, COUNT(*) as barcount FROM table GROUP BY bar ORDER BY barcount
给了我
BAR barcount
----+----
bar1 3
bar2 1
bar3 3
bar4 2
但是我想要实现的是有一张桌子,我知道有多少“酒吧”的酒吧数量为1,有多少人的酒吧数量是2倍,有多少人的酒吧数量是3etc。
我需要的是,为了简单起见:
barcount occurences
--------+-----------
1 1
2 1
3 2
是否可以在单个SQL查询中执行此操作,还是必须依赖某些代码?
答案 0 :(得分:2)
select barcount, count(*) as occurences
from
(
SELECT bar, COUNT(*) as barcount
FROM your_table
GROUP BY bar
) tmp
group by barcount
答案 1 :(得分:1)
如果需要嵌套聚合,则必须使用派生表(或公用表表达式):
select barcount, count(*) as occurrences
from
(
SELECT bar, COUNT(*) as barcount
FROM table
GROUP BY bar
) as dt
group by barcount
ORDER BY barcount
答案 2 :(得分:0)
您可以将查询包装在另一个查询中:
SELECT barcount, COUNT(*) AS occurences
FROM (SELECT bar, COUNT(*) as barcount
FROM mytable
GROUP BY bar) t
GROUP BY barcount
ORDER BY barcount