我正在练习一些SQL,我想到了以下问题:
对于每个酒吧,找到更多人去的时间。 我有以下表格:
GOESTO id_person id_pub time 1 1 Daytime 2 2 Night time 3 3 All Day 4 1 Daytime 5 2 Night time 6 1 All Day 7 3 Daytime 8 3 Night time 9 3 Night time 10 1 Night time
PUB id_pub pub_name cost 1 pub1 123 2 pub2 324 3 pub3 345
我想得的是以下内容:
pub_name time
我认为我应该使用MAX和COUNT函数,但我不确定应该怎么做。它应该在Oracle数据库中工作。
谢谢!
答案 0 :(得分:0)
试试这个:
WITH mydata AS (
select id_pub, "TIME", count(*) as cnt
from GOESTO
group by id_pub, "TIME"
)
SELECT m.id_pub, m."TIME", m.cnt
FROM mydata m
JOIN (
SELECT id_pub, max( cnt ) as cnt
FROM mydata
GROUP BY id_pub
) x
ON (m.id_pub = x.id_pub AND m.cnt = x.cnt);
或者这个
SELECT id_pub, "TIME"
FROM (
SELECT t.*,
dense_rank() over (partition by id_pub order by cnt desc ) rnk
FROM (
select id_pub, "TIME", count(*) as cnt
from GOESTO
group by id_pub, "TIME"
) t
)
WHERE rnk = 1
要获取名称而不是id_pub
值,您需要使用PUB
表
SELECT p.pub_name, q."TIME"
FROM ( one_of_the_above_query )q
JOIN PUB p
ON p.id_pub = q.id_pub