sql-server - 在 T-SQL 中创建月度报告
问题描述
我有一个包含以下列的表格
CaseID
DateLogged
CompletionDate
我正在尝试创建每月库存报告。
例如,我需要每月确定哪些案件是新的、当前的和已完成的,例如,仅在 8 月记录的所有案件都是新案件,而在 8 月完成的所有案件都将显示已完成,所有记录的未完成案件将是最新的。
DROP TABLE IF EXISTS #temptable
-- Create date variables
SET dateformat ymd
DECLARE @datefrom datetime = CONVERT(DATETIME, '2019-04-01 00:00:00', 121)
DECLARE @dateto datetime = (SELECT CAST(DATEADD(DAY, -DAY(GETDATE()), GETDATE()) AS date))
-- Recursive date table creation
;WITH monthserial AS
(
SELECT @datefrom AS monthdate
UNION ALL
SELET DATEADD(MONTH, 1, monthdate)
FROM monthserial
WHERE monthdate < @dateto
)
SELECT MN.*
INTO #temptable
FROM monthserial MN
SELECT * FROM MainTable VW
CROSS JOIN #temptable TBL
WHERE DateLogged <= monthdate) test
解决方案
您需要针对您的情况使用 case-when:
select CaseID,
case
when not (CompletionDate is null) then 'Completed'
when DateLogged >= @input then 'New'
else 'Current'
end
from yourtable
order by DateLogged;
编辑
由于我们对最后一个条目感兴趣,我们可以添加一个 where 子句,如下所示:
select CaseID,
case
when not (CompletionDate is null) then 'Completed'
when DateLogged >= @input then 'New'
else 'Current'
end
from yourtable
where not exists (
select 1
from yourtable inner
where inner.CaseID = yourtable.CaseID and inner.CompletionDate < yourtable.CompletionDate
)
order by DateLogged;
推荐阅读
- powershell - 使用 powershell 从共享点下载特定文件夹的 CAML 查询
- c++ - 找到从**根到叶**的二叉树的所有节点,其总和等于目标总和
- c# - 如何在不知道文件路径的情况下使用 C# 在 Outlook 中找到实现文件夹
- python - Tensorflow 2.0:自定义 keras 指标导致 tf.function 回溯警告
- javascript - 如何让这个 div 在屏幕的一半上滑动?
- python - 为什么在存储 fetchone() 值时显示 TypeError?
- c# - 如何获取具有特定扩展名的所有文件,而不会导致 IOException 告诉我我要访问的文件仍在使用中
- xcode - Xcode 助手“迅速”消耗大量内存
- windows - 在 SFTP 批处理文件中包含密码
- android - 新频道默认禁用通知声音