首页 > 解决方案 > 在 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 

标签: sql-servertsql

解决方案


您需要针对您的情况使用 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;

推荐阅读