假设我们有桌子:
create table EVENT("id" number, "date" DATE, "value" number);
我希望获得每个选中的 id N 或更多次的所有行。所以:
id | date | value -------------------------- 1 | 2011-01-01 | 100 1 | 2011-01-02 | 200 2 | 2011-01-05 | 300 2 | 2011-03-15 | 800 3 | 2011-02-01 | 400 4 | 2011-01-01 | 500 4 | 2011-04-21 | 600 4 | 2011-01-01 | 700
和 N == 2我得到除 id = 3 之外的所有行,对于 N == 3我只获得< EM> ID = 4 ...
我使用Oracle但似乎这种类型的查询需要一些新的SQL知识...
答案 0 :(得分:6)
SELECT "id",
"date",
"value"
FROM (SELECT EVENT.*,
COUNT(*) OVER (PARTITION BY "id") AS CNT
FROM EVENT)
WHERE CNT >= 3
答案 1 :(得分:2)
SELECT *
FROM Event
WHERE Id IN (SELECT Id
FROM Event
GROUP BY Id
HAVING COUNT(*) > N)
编辑:Martin Smith的答案应该是最好的表现,唯一的缺点是你必须列出字段以避免在结果中包含COUNT()。
答案 2 :(得分:1)
select *
from Event
where id in
(
select id
from Event
group by
id
having count(*) > 3 -- For N = 3
)
答案 3 :(得分:1)
你走了:
SELECT *
FROM tmp
WHERE id IN (SELECT id FROM tmp GROUP BY id
HAVING COUNT(*) > N)
根据您的条件更新N
的值。
答案 4 :(得分:1)
SELECT * FROM Event
INNER JOIN (
SELECT id, COUNT(*) AS Cnt FROM Event GROUP BY id
) AS C ON Event.id = C.id
WHERE C.Cnt >= 3
答案 5 :(得分:1)
select
e.*
from
event e,
(select e1.id, count(*) as id_num from event e1 group by e1.id) as e2
where
e.id = e2.id
and e2.id_num >= 3
答案 6 :(得分:0)
SELECT *
FROM EVENT
GROUP BY "id"
HAVING ( COUNT("id") > N - 1
AND COUNT("id") < N + 1 );