从选择查询中选择特定记录

时间:2015-04-19 13:08:39

标签: sql oracle

编辑:我的实际选择如下:

select x.id, x.name, x.status, y.edit, y.date
, LEAD(y.date) OVER ( PARTITION BY x.id ORDER BY y.date ) - date AS edit_diff
from (table1 x left join table2 y on x.id = y.id)
where x.id = 1  

结果如下:

ID    Name    Status    Edit    Date          edit_diff
1     n1      closed    edt1      01/01/2005  6
1     n1      closed    edt1      07/01/2005  8
1     n1      closed    edt2      15/01/2005  5
1     n1      closed    edt2      20/01/2005  3
1     n1      closed    edt3      23/01/2005  null

我实际上希望我的选择仅返回具有最早日期的编辑:

ID    Name    Status    Edit    Date          edit_diff
1     n1      closed    edt1      01/01/2005  14
1     n1      closed    edt2      15/01/2005  8
1     n1      closed    edt3      23/01/2005  null
你能帮忙吗?我尝试了(SELECT edit from mytable WHERE DATE = MAX(DATE)),但由于我在同一个查询上order by,因此无法正常工作。感谢。

1 个答案:

答案 0 :(得分:2)

您可以使用row_number()为每个编辑分配一个顺序值,然后选择第一个:

SELECT id, name, status, edit, date, edit_diff
FROM (SELECT id, name, status, edit, date,
             LEAD(date) OVER ( PARTITION BY id ORDER BY date ) - date AS edit_diff,
             ROW_NUMBER() OVER (PARTITION BY id, edt ORDER BY date) as seqnum
      FROM mytable
     ) t
WHERE seqnum = 1;

仔细观察,您不是选择行而是聚合它们。所以,这似乎更符合您的要求:

SELECT id, name, status, edit, min(date), sum(edit_diff)
FROM (SELECT id, name, status, edit, date,
             LEAD(date) OVER ( PARTITION BY id ORDER BY date ) - date AS edit_diff
      FROM table1 x left join table2 y on x.id = y.id
     ) t
GROUP BY id, name, status, edit;

编辑:

版本应该是:

SELECT id, name, status, edit, min(date), sum(edit_diff)
FROM (SELECT x.id, x.name, x.status, y.edit, y.date,
             LEAD(y.date) OVER (PARTITION BY x.id ORDER BY y.date ) - y.date AS edit_diff
      FROM mytable
      WHERE x.id = 1
     ) t
GROUP BY id, name, status, edit;