2

假设我们有表:

create table EVENT("id" number, "date" DATE, "value" number);

我想获取每个选定id出现N次或更多次的所有行。因此对于:

    编号 | 日期 | 价值
   --------------------------
    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 我只得到id=4的行......

我与 Oracle 合作,但似乎这种类型的查询对我来说需要一些新的 SQL 知识......

4

7 回答 7

6
SELECT "id",
       "date",
       "value"
FROM   (SELECT EVENT.*,
               COUNT(*) OVER (PARTITION BY "id") AS CNT
        FROM   EVENT)
WHERE  CNT >= 3 

SQL小提琴

于 2013-06-20T12:24:23.423 回答
2
SELECT *
FROM Event
WHERE Id IN (SELECT Id 
             FROM Event
             GROUP BY Id 
             HAVING COUNT(*) > N)

编辑:马丁史密斯的答案应该有最好的表现,唯一的缺点是你必须列出字段以避免在结果中包含 COUNT() 。

于 2013-06-20T12:22:32.963 回答
1

干得好:

SELECT *
FROM tmp
WHERE id IN (SELECT id FROM tmp GROUP BY id 
             HAVING COUNT(*) > N)

N根据您的情况更新值。

SQL 小提琴演示

于 2013-06-20T12:29:11.223 回答
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
于 2013-06-20T12:29:48.137 回答
1
select  *
from    Event
where   id in
        (
        select  id
        from    Event
        group by
                id
        having  count(*) > 3 -- For N = 3
        )
于 2013-06-20T12:22:23.553 回答
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
于 2013-06-20T12:36:36.437 回答
0
SELECT *
FROM   EVENT
GROUP  BY "id"
HAVING ( COUNT("id") > N - 1
         AND COUNT("id") < N + 1 ); 
于 2013-06-20T12:35:18.570 回答