Hi I need to insert all dates between startdate and enddate of a casenumber is SQL (ssms). So instead of having one row per casenumber the casenumber will have a row for each day. So if there is 10 days between the case started and ended it will have 10 rows. If the case has not been ended it will have a NULL in the original table but should be replaced with getdate. See attach image.
image of tables
This achieves your picture:
Test Data Setup
create table #test (CaseNumber int, StartDate date, Enddate date)
insert into #test (CaseNumber, StartDate, Enddate)
values(1,'2019-09-18','2019-09-24'),(2,'2019-09-23',NULL)
The Code
;with dt_seq as (
select t.CaseNumber, t.StartDate, isnull(t.Enddate,cast (getdate() as date)) EndDate, t.StartDate [Date]
from #test t
union all
select z.CaseNumber, z.StartDate, z.EndDate, case when z.[Date] < z.EndDate then dateadd(day,1,z.[Date]) else z.EndDate end [Date]
from dt_seq z
where z.[Date] <= dateadd(day,-1,z.EndDate)
)
select c.*, ROW_NUMBER() over (partition by c.CaseNumber order by c.[Date]) [Duration]
from dt_seq c
order by c.CaseNumber, c.[Date]
option ( MaxRecursion 0 )
Reuslts
Related
I have 2 dates, StartDate and EndDate:
Declare #StartDate date='2018/01/01', #Enddate date ='2018/12/31'
Then there is some data with a date and value in a mytable table:
----------------------------
ID date value
----------------------------
1 2018/02/14 4
2 2018/09/26 7
3 2017/09/20 2
data maybe start before 2018 and if it exist before #startdate get before values
else get 0
I'm looking to get a result that looks like this:
-----------------------------------
fromdate todate value
-----------------------------------
2018/01/01 2018/02/13 2
2018/02/14 2018/09/25 4
2018/09/26 2018/12/31 7
The first fromdate comes from #StartDate and the last todate is from #Enddate, and the other data should be generated.
I'm hoping to get this in an SQL query. I use sql-server 2016
You could use a CTE to create your full range of dates, and then LEAD to create the ToDate column:
DECLARE #FromDate date = '20180101',
#ToDate date = '20181231';
WITH VTE AS(
SELECT ID,
CONVERT(date,[date]) [date], --This is why using keywords for column names is a bad idea
[value]
FROM (VALUES(1,'20180214',4),
(2,'20180926',7),
(3,'20170314',4))V(ID,[date],[value])),
Dates AS(
SELECT [date]
FROM VTE V
WHERE V.[date] BETWEEN #FromDate and #ToDate
UNION ALL
SELECT [date]
FROM (VALUES(#FromDate))V([date]))
SELECT D.[date] AS FromDate,
LEAD(DATEADD(DAY, -1,D.[date]),1,#ToDate) OVER (ORDER BY D.[date]) AS ToDate,
ISNULL(V.[value],0) AS [value]
FROM Dates D
LEFT JOIN VTE V ON D.[date] = V.[date];
db<>fiddle
with cte as
(
select 0 as row_num, #StartDate as start_date, 0 as val
UNION
select ROW_NUMBER() OVER(ORDER BY start_date) as row_num, * from input
)
select curr.start_date
, DATEADD(day,-1,ISNULL(nex.start_date,DATEADD(day,1,#Enddate))) as end_date
, curr.val
from cte curr
left join cte nex on curr.row_num = nex.row_num - 1;
You can find the simulation here: https://rextester.com/EIAXW23839
I have table with below data -
StartDate EndDate Amount
2/1/2016 4/30/2016 2.265
2/1/2016 12/31/2099 16.195
5/1/2016 12/31/2099 37.75
I am trying to write a query to sum the amount on date range and give me below result
StartDate EndDate Amount
2/1/2016 4/30/2016 18.46
5/1/2016 12/31/2099 53.945
The result needs to be distinct date range with amount summed for that date range. As in above example, row 2 has dates that overlap row 1 and 3. So the row 2 amount needs to be added in row 1 and row 3.
I am writing this query on sql server 2012, Please advise on what approach I should take.
Below is query to generate sample data
SELECT * INTO #tmp_GridResults_1
FROM (
SELECT N'2016-02-01 00:00:00.000' AS [StartDate], N'2016-04-30 00:00:00.000' AS [EndDate], N'2.265' AS [Amount] UNION ALL
SELECT N'2016-02-01 00:00:00.000' AS [StartDate], N'2099-12-31 00:00:00.000' AS [EndDate], N'16.195' AS [Amount] UNION ALL
SELECT N'2016-05-01 00:00:00.000' AS [StartDate], N'2099-12-31 00:00:00.000' AS [EndDate], N'37.75' AS [Amount] ) t;
SELECT [StartDate], [EndDate], [Amount]
FROM #tmp_GridResults_1
I don't think you'll be able to group with both StartDate and EndDate. However, if you use just StartDate and Amount you can try this:
select StartDate,sum(Amount) as Amount from #tmp_GridResults_1 group by StartDate
This will give you the grouping of Amount by StartDate.
From my previews comment i think you want to group by StartDate, in that case you can use:
SELECT
mt.StartDate,
SUM(Amount) AS 'Amount'
FROM MyTable mt
WHERE mt.StartDate BETWEEN
'2016-05-18 00:00:00.000' AND '2016-06-20 00:00:00.000' --your date range
GROUP BY StartDate
However you need to specify in your question how you want to group them, because with 2 date fields you can group the following ways:
GROUP BY StartDate --groups records that have the same StartDate
GROUP BY EndDate --groups records that have the same EndDate
GROUP BY StartDate, EndDate --groups records that have same StartDate and EndDate
Also with 2 date fields your date range can vary a lot.
WHERE StartDate BETWEEN #sd AND #ed --will get records whose start date is inside the provided range
WHERE EndDate BETWEEN #sd AND #ed --will get records whose end date is inside the provided range
WHERE StartDate >= #sd AND EndDate <= #ed -- will get records that started and ended inside the provided date range
WHERE StartDate BETWEEN #sd AND #ed OR EndDate BETWEEN #sd AND #ed
--this last one will get records whose StartDate or EndDate are inside the provided date range
based on this you can build the query that you need, but with the provided data in your question its still ambiguous what you want to achieve, you need to be more specific and provide more data in order to produce an exact answer to your question.
One more thing to add is that if you take into account time it will not group them if the date is the same but time is different i.e.
'2016-05-18 00:00:00.000'
'2016-05-18 01:01:01.001'
--these dates will not be grouped
Below query will give the required result :-
select StartDate,EndDate,SUM(Amount) over (partition by StartDate) AS Amount into #t1
from table_name
select StartDate,EndDate,SUM(Amount) over (partition by EndDate) AS Amount into #t2
from table_name
select * from (
select distinct P.StartDate,P.EndDate,P.Amount from (
select StartDate,MIN(EndDate) EndDate,Amount from #t1
group by StartDate,Amount) P
JOIN (
select MIN(StartDate) StartDate,EndDate,Amount from #t2
group by EndDate,Amount) Q on P.StartDate=Q.StartDate OR P.EndDate=Q.EndDate
where P.Amount>=Q.Amount
UNION
select distinct P.StartDate,P.EndDate,P.Amount from (
select MIN(StartDate) StartDate,EndDate,Amount from #t2
group by EndDate,Amount) P
JOIN (
select StartDate,MIN(EndDate) EndDate,Amount from #t1
group by StartDate,Amount) Q on P.StartDate=Q.StartDate OR P.EndDate=Q.EndDate
where P.Amount>=Q.Amount
) A
Just Replace table_name by the table for which you want result, Let me know in case of any confusion
I have a query as following:
SELECT [Date] FROM [TableX] ORDER BY [Date]
The result is:
2016-06-01
2016-06-03
2016-06-10
2016-06-11
How can I get following pairs?
From To
2016-06-01 2016-06-03
2016-06-03 2016-06-10
2016-06-10 2016-06-11
If you're using SQL Server 2012 or later, you can use the LEAD method.
Accesses data from a subsequent row in the same result set without the use of a self-join in SQL Server 2016. LEAD provides access to a row at a given physical offset that follows the current row.
I think it would look like this for you:
SELECT [Date] AS [From], LEAD([Date], 1) OVER (ORDER BY [Date]) AS [To]
FROM TableX
ORDER BY [Date]
Note that on the last row, the [To] field will be NULL. If you wanted to remove that row, you could put it in an inner query:
SELECT *
FROM
(
SELECT [Date] AS [From], LEAD([Date], 1) OVER (ORDER BY [Date]) AS [To]
FROM TableX
) x
WHERE [To] IS NOT NULL
All you need to do is add a row number for each date.
Then unite all these rows by the next row (except the last row)
WITH cteDates AS
(
SELECT [Date],
ROW_NUMBER() OVER (ORDER BY (SELECT [Date])) As RowNum
FROM TableX
)
SELECT TOP(SELECT COUNT(*) - 1 FROM cteDates)
[Date] [From],
(SELECT [Date] FROM cteDates WHERE RowNum = d.RowNum + 1) [To]
FROM cteDates d
A little tricky solution for SQL 2008.
declare #tbl table(dt datetime)
insert #tbl values
('2016-06-01'),
('2016-06-03'),
('2016-06-10'),
('2016-06-11')
;with cte as (
select dt, ROW_NUMBER() over(order by dt) rn --add number
from #tbl
),
newTbl as (
select t1.dt start, t2.dt [end]
from cte t1 inner join cte t2 on t1.rn+1=t2.rn
)
select *
from newTbl
The result is what you wish.
Since there are never any gaps as you stated, you can just used DATEADD()
SELECT DISTINCT
[Date] as [FROM],
DATEADD(DAY,1,[Date]) as [TO]
FROM TableX
ORDER BY [Date] DESC
What I need is to calculate the missing time periods within the calendar year given a table such as this in SQL:
DatesTable
|ID|DateStart |DateEnd |
1 NULL NULL
2 2015-1-1 2015-12-31
3 2015-3-1 2015-12-31
4 2015-1-1 2015-9-30
5 2015-1-1 2015-3-31
5 2015-6-1 2015-12-31
6 2015-3-1 2015-6-30
6 2015-7-1 2015-10-31
Expected return would be:
1 2015-1-1 2015-12-31
3 2015-1-1 2015-2-28
4 2015-10-1 2015-12-31
5 2015-4-1 2015-5-31
6 2015-1-1 2015-2-28
6 2015-11-1 2015-12-31
It's essentially work blocks. What I need to show is the part of the calendar year which was NOT worked. So for ID = 3, he worked from 3/1 through the rest of the year. But he did not work from 1/1 till 2/28. That's what I'm looking for.
You can do it using LEAD, LAG window functions available from SQL Server 2012+:
;WITH CTE AS (
SELECT ID,
LAG(DateEnd) OVER (PARTITION BY ID ORDER BY DateEnd) AS PrevEnd,
DateStart,
DateEnd,
LEAD(DateStart) OVER (PARTITION BY ID ORDER BY DateEnd) AS NextStart
FROM DatesTable
)
SELECT ID, DateStart, DateEnd
FROM (
-- Get interval right before current [DateStart, DateEnd] interval
SELECT ID,
CASE
WHEN DateStart IS NULL THEN '20150101'
WHEN DateStart > start THEN start
ELSE NULL
END AS DateStart,
CASE
WHEN DateStart IS NULL THEN '20151231'
WHEN DateStart > start THEN DATEADD(d, -1, DateStart)
ELSE NULL
END AS DateEnd
FROM CTE
CROSS APPLY (SELECT COALESCE(DATEADD(d, 1, PrevEnd), '20150101')) x(start)
-- If there is no next interval then get interval right after current
-- [DateStart, DateEnd] interval (up-to end of year)
UNION ALL
SELECT ID, DATEADD(d, 1, DateEnd) AS DateStart, '20151231' AS DateEnd
FROM CTE
WHERE DateStart IS NOT NULl -- Do not re-examine [Null, Null] interval
AND NextStart IS NULL -- There is no next [DateStart, DateEnd] interval
AND DateEnd < '20151231' -- Current [DateStart, DateEnd] interval
-- does not terminate on 31/12/2015
) AS t
WHERE t.DateStart IS NOT NULL
ORDER BY ID, DateStart
The idea behind the above query is simple: for every [DateStart, DateEnd] interval get 'not worked' interval right before it. If there is no interval following the current interval, then also get successive 'not worked' interval (if any).
Also note that I assume that if DateStart is NULL then DateStart is also NULL for the same ID.
Demo here
If your data is not too big, this approach will work. It expands all the days and ids and then re-groups them:
with d as (
select cast('2015-01-01' as date)
union all
select dateadd(day, 1, d)
from d
where d < cast('2015-12-31' as date)
),
td as (
select *
from d cross join
(select distinct id from t) t
where not exists (select 1
from t t2
where d.d between t2.startdate and t2.enddate
)
)
select id, min(d) as startdate, max(d) as enddate
from (select td.*,
dateadd(day, - row_number() over (partition by id order by d), d) as grp
from td
) td
group by id, grp
order by id, grp;
An alternative method relies on cumulative sums and similar functionality that is much easier to expression in SQL Server 2012+.
Somewhat simpler approach I think.
Basically create a list of dates for all work block ranges (A). Then create a list of dates for the whole year for each ID (B). Then remove the A from B. Compile the remaining list of dates into date ranges for each ID.
DECLARE #startdate DATETIME, #enddate DATETIME
SET #startdate = '2015-01-01'
SET #enddate = '2015-12-31'
--Build date ranges from remaining date list
;WITH dateRange(ID, dates, Grouping)
AS
(
SELECT dt1.id, dt1.Dates, dt1.Dates + row_number() over (order by dt1.id asc, dt1.Dates desc) AS Grouping
FROM
(
--Remove (A) from (B)
SELECT distinct dt.ID, tmp.Dates FROM DatesTable dt
CROSS APPLY
(
--GET (B) here
SELECT DATEADD(DAY, number, #startdate) [Dates]
FROM master..spt_values
WHERE type = 'P' AND DATEADD(DAY, number, #startdate) <= #enddate
) tmp
left join
(
--GET (A) here
SELECT DISTINCT T.Id,
D.Dates
FROM DatesTable AS T
INNER JOIN master..spt_values as N on N.number between 0 and datediff(day, T.DateStart, T.DateEnd)
CROSS APPLY (select dateadd(day, N.number, T.DateStart)) as D(Dates)
WHERE N.type ='P'
) dr
ON dr.Id = dt.Id and dr.Dates = tmp.Dates
WHERE dr.id is null
) dt1
)
SELECT ID, CAST(MIN(Dates) AS DATE) DateStart, CAST(MAX(Dates) AS DATE) DateEnd
FROM dateRange
GROUP BY ID, Grouping
ORDER BY ID
Heres the code:
http://sqlfiddle.com/#!3/f3615/1
I hope this helps!
I have a table, part of which is given below. It contain multiple values (durations) per day. I need two things 1) addition of durations per day. 2) plotting them on calendar in such a way that startdate is first_date from the table and last_date is Last_update from the table. I want to mention 0 for which date there is no duration. I think it will something like below but need help.
;WITH AllDates AS(
SELECT #Fromdate As TheDate
UNION ALL
SELECT TheDate + 1
FROM AllDates
WHERE TheDate + 1 <= #ToDate
)SELECT UserId,
TheDate,
COALESCE(
SUM(
-- When the game starts and ends in the same date
CASE WHEN DATEDIFF(DAY, GameStartTime, GameEndTime) = 0
Here is what I am looking for
Another way to generate the date range you are after would be something like .....
;WITH DateLimits AS
(
SELECT MIN(First_Date) FirstDate
,MAX(Last_Update) LastDate
FROM TableName
),
DateRange AS
(
SELECT TOP (SELECT DATEDIFF(DAY,FirstDate,LastDate ) FROM DateLimits)
DATEADD(DAY
,ROW_NUMBER() OVER (ORDER BY (SELECT NULL))
, (SELECT FirstDate FROM DateLimits)
) AS Dates
FROM master..spt_values a cross join master..spt_values b
)
SELECT * FROM DateRange --<-- you have the desired date range here
-- other query whatever you need.