[英]SQL Carryover from previous month
我有一些数据正在尝试依靠。 有记录输入的时间和记录关闭的日期(如果尚未关闭)。 我希望能够统计到截至本月第一天为止上个月还有多少条记录处于打开状态。 这是一个例子。 第一个表是数据,第二个表是我正在寻找的结果。 在第二个表中,忽略括号,它们只是构成该计数的记录的ID。
Position DateEntered DateClosed
1 12/15/2017 12/20/2017
11 12/20/2017 1/7/2018
2 1/23/2018 2/3/2018
3 1/24/2018
4 2/15/2018
5 2/20/2018 5/16/2018
6 3/3/2018 3/15/2018
7 3/23/2018 4/12/2018
8 4/11/2018 5/10/2018
9 4/12/2018 4/25/2018
10 5/4/2018
Year Month Carried Over
2018 January 1 (11)
2018 February 2 (2,3)
2018 March 3 (3,4,5)
2018 April 4 (3,4,5,7)
2018 May 4 (3,4,5,8)
2018 June 3 (3,4,10)
2018 July 3 (3,4,10)
2018 August 3 (3,4,10)
这可能吗?如果可以,怎么办? 在这上面花了我几个小时的时间。
对于每个月,您需要在该月之前开始并在此之后结束的行数。 我在想:
with dates as (
select cast('2018-01-01' as date) as dte
union all
select dateadd(month, 1, dte)
from dates
where dte < '2018-08-01'
)
select d.dte,
(select count(*)
from t
where t.dateentered < d.dte and
(t.dateclosed > d.dte or t.dateClosed is null)
) as carriedover
from dates d;
请注意,这会将日期放在单个列中,而不是将年和月分成不同的列。 这很容易安排,但我更喜欢将日期部分放在一起。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.