我有一张这样的桌子:
TICKET ID | OPEN DATE | CLOSE DATE
----------+------------+------------
1 | 2018-12-30 | 2019-01-01
2 | 2019-01-30 | 2019-02-01
3 | 2019-01-20 | 2019-01-22
我必须生成一个视图,该视图为每个票证ID为当年的每个月创建几个状态(打开,关闭,积压)的条目。如果打开日期为月份,则状态为OPEN;如果关闭日期为月份,则状态为CLOSED;如果打开日期为上个月的日期,则为LOGLOG;如果关闭日期为上个月的日期,则为STATLOG。
因此在下面的示例中,输出表将是:
TICKET ID | MONTH | STATUS
----------+--------+---------
1 | JAN-19 | BACKLOG
1 | JAN-19 | CLOSED
2 | JAN-19 | OPEN
3 | JAN-19 | OPEN
3 | JAN-19 | CLOSED
2 | FEB-19 | CLOSED
有没有办法在SQL Server的纯SQL中做到这一点?
答案 0 :(得分:0)
这是您想要的吗?您可以通过调整日期表来调整运行周期。
declare @tickets table (ticketId int, openDate datetime, closeDate datetime)
insert into @tickets (ticketId, openDate, closeDate) values (1, '30 Dec 2018', '1 Jan 2019')
insert into @tickets (ticketId, openDate, closeDate) values (2, '30 Jan 2019', '1 Feb 2019')
insert into @tickets (ticketId, openDate, closeDate) values (3, '20 Jan 2019', '22 Jan 2019')
; with dates as (
select cast('1 Jan 2019' as datetime) startMon, cast('31 Jan 2019' as dateTime) endMon
union all
select dateAdd(mm, 1, startMon), DATEADD(dd, -1, dateAdd(mm, 2, startMon)) from dates where startMon < '01 Dec 2019'
)
select ticketId, startMon, 'BACKLOG' [Status] from @tickets t inner join dates d on t.openDate between dateAdd(m, -1, startMon) and startMon and closeDate < endMon and closeDate >= startMon
union
select ticketId, startMon, 'OPEN' from @tickets t inner join dates d on t.openDate between startMon and endMon
union
select ticketId, startMon, 'CLOSED' from @tickets t inner join dates d on t.closeDate between startMon and endMon
order by startMon, ticketId
答案 1 :(得分:0)
您的描述表明:
select t.ticket_id, v.mon, v.status
from t cross apply
(values ('OPEN', datefromparts(year(open_date), month(open_date), 1)),
('CLOSED', datefromparts(year(open_date), month(open_date), 1)),
('BACKLOG', datefromparts(year(dateadd(month, 1, open_date)), month(dateadd(month, 1, open_date)), 1))
) v(status, mon)
where status <> 'BACKLOG' or
datediff(month, open_date, close_date) > 0;
您可以在where
子句中添加特定时间段的过滤条件,例如2019年的日期。
这应该完全满足您对“待办事项”的要求:
BACKLOG(如果打开日期是上个月,而关闭日期不是上个月)。
但是,您没有考虑多个月的积压。如果有可能,请问一个 new 问题,并提供适当的样本数据和所需的结果。