Oracle SQL-如何返回每个ID的最早/分钟日期的记录[重复]

问题描述 投票:0回答:1

我有一个查询,该查询当前将返回多个记录,因为它们之间的日期略有不同。我想返回每个ID最早的记录。

示例输出:

ID  AMOUNT  DATE
1   10      1
1   20      2
1   30      3
1   1       4
2   34      1
2   234     2
2   234     3
2   34      4
3   3       1
3   3       2
3   23      3
3   20      4

所需的输出:

ID  AMOUNT  DATE
1   10      1
2   34      1
3   3       1

这是我当前的查询:

SELECT DISTINCT th.somefield21 as field21, 
th.somefield18 AS field18, 
th.somefield17 AS field17, 
(c.somefield19 || ' ' || c.somefield20) AS field19, 
CASE when th.somefield15 = 'TEST' then (b.apple || ' ' || b.bananna || ' ' || b.peach || ' ' || b.plum || ' ' || b.grape) else a.somefield16 END AS field16, 
a.somefield1 AS field1, 
a.somefield2 AS field2, 
a.somefield3 AS field3, 
th.somefield4 AS field4, 
s.somefield5 AS field5, 
th.somefield6 AS field6, 
th.somefield7 AS field7, 
th.somefield8 AS field8, 
s.somefield9 AS field9, 
s.somefield10 AS field10, 
s.somefield11 AS field11, 
s.somefield12 AS field12, 
s.somefield13 AS field13, 
th.somefield14 AS field14 
FROM schema.therm th, 
schema.charlie c, 
schema.faux f, 
schema.alpha a, 
schema.bravo b, 
schma.sierra s, 
schema.delta d, 
schema.golf g, 
schema.echo e, 
schema.foxtrot ft 
  WHERE ft.act='submit' 
     AND ft.tid = th.tid  
     AND ft.aid = c.aid 
     AND c.cid = f.cid 
     AND f.addid = a.addid 
     AND f.addid = b.addid 
     AND th.tid = d.tid 
     AND ft.aid = e.aid
     AND e.dsrid = g.dsrid 
     AND g.dsprid = s.dsprid 
     AND th.ttype = 'c1' 
     AND f.add = 'wookie' 
     AND th.date between to_date('01/01/2001 00:00:00','MM/DD/YYYY HH24:MI:SS') and to_date('10/01/2019 23:59:59','MM/DD/YYYY HH24:MI:SS') 
     AND s.code = 'han' 
     AND th.state != 'darth' 
     AND d.act NOT IN ('peach','pear','cherry','plum') 
ORDER BY th.field21;

这将导致多个记录具有相同ID的条目。

我尝试添加min(th.somefield18 AS field18,),但结果是

ORA-00937: not a single-group group function
00937. 00000 -  "not a single-group group function".

[当我尝试添加GROUP BY field19时会产生

ORA-00979: not a GROUP BY expression
00979. 00000 -  "not a GROUP BY expression"
sql oracle11g greatest-n-per-group
1个回答
0
投票

使用相关子查询:

select t.*
from mytable t
where t.date = (
    select min(t1.date)
    from mytable t1
    where t1.id = t.id
)

[在(id, date)上具有索引,应该具有良好的效率。

另一种选择是使用窗口函数在具有相同id的记录组中对记录进行排名,然后在每组的顶部记录上进行过滤:

select id, date
from (
    select t.*, rank() over(partition by t.id order by t.date) rn
    from mytable t
) t
where rn = 1

注意:您的查询比示例数据复杂得多。这回答了示例数据中描述的用例。

© www.soinside.com 2019 - 2024. All rights reserved.