首页 > 解决方案 > SQL 根据交易历史建立清单

问题描述

我有一个项目在一段时间内发生的交易表。我想创建个人库存在任何特定日期将包含的内容的快照历史记录。

| Item ID    | Status      | Person       | Date         |
|:-----------|------------:|:------------:|:------------:|
| 1000       | Created     | NULL         | 11-25-19     |
| 1000       | Checked Out | John Doe     | 11-26-19     |    
| 1000       | Edited      | John Doe     | 11-26-19     |   
| 2000       | Created     | NULL         | 11-27-19     |
| 2000       | Checked Out | John Doe     | 11-27-19     |  
| 1000       | Checked In  | John Doe     | 11-29-19     |
| 1000       | Edited      | John Doe     | 11-29-19     |

对于上面的例子:

这可以用我当前的表结构来完成吗?我认为选择每个项目 ID 的 TOP 1,其中 Person 在所选日期之前不为 NULL 应该可以解决问题。

这是我尝试过的:

;WITH cte AS
(
     SELECT *,
     ROW_NUMBER() OVER (PARTITION BY ItemID ORDER BY ActionDate DESC) 
     AS rn
     FROM [History]
     WHERE [History].ActionDate < Convert(datetime, DATEADD(day, +1, 
     @Date)) AND ([History].Person IS NOT NULL)
)
SELECT *
FROM cte
WHERE rn = 1
ORDER BY cte.ActionDate

标签: sqlsql-server

解决方案


我想你想看看在没有“签入”的日期之前是否有“签出”。

如果是这样,您可以使用相关子查询:

select h.*
from history h
where exists (select 1
              from history h2
              where h2.person = h.person and
                    h2.itemid = h.itemid and
                    h2.date < h.date
                    h2.status = 'Check Out'
             ) and
      not exists (select 1
                  from history h2
                  where h2.person = h.person and
                        h2.itemid = h.itemid and
                        h2.date < h.date
                        h2.status = 'Check In'
                 );

推荐阅读