[英]SQL Carryover from previous month
I have some data that I am trying to get some counts on. 我有一些数据正在尝试依靠。 There are dates for when the record was entered and when it was closed, if it has been closed yet.
有记录输入的时间和记录关闭的日期(如果尚未关闭)。 I want to be able to get a count of how many records were still open from the previous month as of the first of the month.
我希望能够统计到截至本月第一天为止上个月还有多少条记录处于打开状态。 Here is an example.
这是一个例子。 First table is the data, second table is the results I am looking for.
第一个表是数据,第二个表是我正在寻找的结果。 In the second table, ignore the parenthesis, they are just the IDs of the records that make up that count.
在第二个表中,忽略括号,它们只是构成该计数的记录的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)
Is this possible, and if so, how? 这可能吗?如果可以,怎么办? Been racking my brain on this one for a few hours.
在这上面花了我几个小时的时间。
For each month, you want the number of rows that start before that month and end after. 对于每个月,您需要在该月之前开始并在此之后结束的行数。 I'm thinking:
我在想:
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;
Note that this puts the date in a single column, rather than splitting the year and month into separate columns. 请注意,这会将日期放在单个列中,而不是将年和月分成不同的列。 That is easily arranged, but I prefer to keep date components together.
这很容易安排,但我更喜欢将日期部分放在一起。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.