选择SQL内部联接并省略某些记录

时间:2014-01-18 17:09:37

标签: sql postgresql

我有两张包含以下数据的表格:

表A

ID       DESC
1        One
2        Two
3        Three

ID是主键

表B显示了我对表A中的ID所做的操作

NO       ACTION       ID       DATETIME
1        ADD          1        2012-01-01 00:00:00
2        ADD          2        2012-01-01 00:00:00
3        ADD          3        2012-01-01 00:00:00
4        DELETE       2        2012-01-01 01:00:00
5        EDIT         1        2012-01-01 02:00:00
6        EDIT         3        2012-01-01 03:00:00
7        DELETE       1        2012-01-01 03:00:00
8        REVIVE       2        2012-01-01 04:00:00
9        EDIT         2        2012-01-01 05:00:00

NO是主键

以下是摘要:

ID 1:ADD on 2012-01-01 00:00:00,EDIT on 2012-01-01 02:00:00,DELETE on 2012-01-01 03:00:00

ID 2:ADD on 2012-01-01 00:00:00,DELETE on 2012-01-01 01:00:00,REVIVE on 2012-01-01 04:00:00,EDIT on 2012-01 -01 05:00:00

ID 3:ADD on 2012-01-01 00:00:00,EDIT on 2012-01-01 03:00:00

如何查询表格以获得以下结果:

表C

NO       DESC
2        Two
3        Three

我想要做的是:在最后一个交易时间查询表A没有DELETE操作,这样我只得到活动ID

我试图进行内部联接,但是在如何省略在最后一个事务时间删除操作的ID时遇到了问题。任何建议/意见将不胜感激。

2 个答案:

答案 0 :(得分:1)

你可以试试这个

select ID, DESC
from A join (
select id, action, rank() over (partition by id order by datetime desc) ranking
from B
) B on (B.ranking = 1 and B.id = A.id and B.action <> 'DELETE')

答案 1 :(得分:0)

假设NOTableB的主键,则根据DATETIME订购:

select 
  TableA.ID, TableA.DESC
from TableA inner join 
  (select ID, max(NO) as MaxNO from TableB group by ID) as MaxNOs
    on TableA.ID = MaxNOs.ID
      inner join TableB on MaxNOs.ID = TableB.ID and MaxNOs.MaxNO = TableB.NO
where
  TableB.ACTION <> 'DELETE'