从历史记录中查询项目 table

Query items from a history table

我有一个“图书馆”历史记录 table(Excel 喜欢)以查看一本书曾经或现在在哪里。

id date book action client
1 2020-12-01 1 toClient 1
2 2020-12-02 1 returned 1
3 2020-12-03 1 toClient 2
4 2020-12-04 2 toClient 2
5 2020-12-05 3 toClient 1
6 2020-12-06 3 returned 1
7 2020-12-07 2 returned 2
8 2020-12-08 2 toClient 1

我正在尝试了解客户 2(例如)有多少本书和哪些书。

我有类似的东西可以找到关于客户 2 现在或以前的书籍的所有信息:

SELECT * FROM history WHERE book IN 
  (SELECT book FROM history WHERE action='toClient' AND client=2 GROUP BY book)

但是,我也得到了客户端 2 上不再有的书。

是否有一种简单的方法来查询最后一个操作是“toClient”而不是“returned”并且当前客户端是客户端 2 的项目?

编辑:忘了写 action 也可以是 revisiontimeExtension 或其他。

要列出当前已售出的图书,您可以执行以下操作:

select h.*
from history h
where 
    action = 'toClient' 
    and h.date = (select max(d1.date) from history h1 where h1.book = h.book)

我们的想法是过滤每本书的最新事件日期。那么我们只保留对应事件为“toClient”的行。

这 returns 所有客户的结果。如果您只需要一个客户端,只需在查询的 where 子句中添加一个附加条件:

and client = 2

您也可以使用 window 函数执行此操作:

select *
from (
    select h.*,
        rank() over(partition by book order by date desc) rn
    from history h
) h
where rn = 1 and action = 'toClient' -- and client = 2