sql - 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 |
对于上面的例子:
- 如果我在哪里为 11-25-19 挑选快照,John Doe 的库存将一无所有。
- 11-26-19 他将拥有项目 1000
- 11-27-19 他将拥有 1000 和 2000
- 11-28-19 他将拥有 1000 和 2000
- 11-29-19 他只拥有 2000
这可以用我当前的表结构来完成吗?我认为选择每个项目 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
解决方案
我想你想看看在没有“签入”的日期之前是否有“签出”。
如果是这样,您可以使用相关子查询:
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'
);
推荐阅读
- javascript - Mongoose find - 从查询中返回所有匹配的至少一个
- julia - Julia中函数调用的歧义
- f# - F# LiteDB [
] 被忽略? - javascript - 如何检查身份验证令牌是否已过期并强制注销?
- android - 如何将雅虎天气 API 中的日期解析为 Java 日期
- javascript - 尝试将 JSON POST 发送到 Discord Webhook 时,urlFetchApp.fetch() 似乎静默失败
- android - 如何将activity_main布局文件连接到非主要活动
- java - .split() 包含字符“++”的字符串
- python - UnicodeDecodeError:“ascii”编解码器无法解码位置 412200 中的字节 0x9a:序数不在范围内(128)
- python - 使用ansible从windows获取文件到远程主机没有被正确复制