sql query to join split date bound records if they are same [duplicate] - sql

This question already has answers here:
SQL: Merge Date Ranges
(3 answers)
Closed 7 years ago.
I have table in which records are date bound. Example
UserID | Amount | StartDate | EndDate
1500 100 1/1/2014 12/31/2014
1500 100 1/1/2015 12/31/2015
1500 50 1/1/2016 12/31/2016
1500 100 1/1/2017 12/31/2099
The desired result that I am trying to get is
UserID Amount StartDate EndDate
1500 100 1/1/2014 12/31/2015
1500 50 1/1/2016 12/31/2016
1500 100 1/1/2017 12/31/2099
If the records are same, I need to join them. Please let me know if you have any suggestions to get the desired result. I need to be able to run the query on sql server 2012.
Thanks,
sql snippet to create a temp table -
IF OBJECT_ID('tempdb..#SplitRecords') IS NOT NULL
DROP TABLE #SplitRecords
CREATE TABLE #SplitRecords
(
UserID INT,
Amount DECIMAL(19,4),
StartDate DATETIME,
EndDate DATETIME
)
INSERT INTO #SplitRecords
( UserID, Amount, StartDate, EndDate )
VALUES ( 1500, -- UserID - int
100, -- Amount - decimal
'1/1/2014', -- StartDate - datetime
'12/31/2014' -- EndDate - datetime
)
INSERT INTO #SplitRecords
( UserID, Amount, StartDate, EndDate )
VALUES ( 1500, -- UserID - int
100, -- Amount - decimal
'1/1/2015', -- StartDate - datetime
'12/31/2015' -- EndDate - datetime
)
INSERT INTO #SplitRecords
( UserID, Amount, StartDate, EndDate )
VALUES ( 1500, -- UserID - int
100, -- Amount - decimal
'1/1/2016', -- StartDate - datetime
'12/31/2016' -- EndDate - datetime
)
INSERT INTO #SplitRecords
( UserID, Amount, StartDate, EndDate )
VALUES ( 1500, -- UserID - int
100, -- Amount - decimal
'1/1/2017', -- StartDate - datetime
'12/31/2099' -- EndDate - datetime
)

Do a left join with first table where there s a group by and min for start date and the second table where you join on with group by and max end date. Does this help you?
I can t write code now but I can tomorrow.

Related

Return number of rows dependent on number

Have a table with this
Id
StartDate
NoOfMonths
1
2021-09-01
2
2
2021-09-01
3
And want a query to return this
Id
Date
1
2021-09-01
1
2021-10-01
2
2021-09-01
2
2021-10-01
2
2021-11-01
How can I make this happen?
Here is an example without an additional table:
DECLARE #t TABLE(
ID int
, StartDate date
, NoOfMonths int
)
INSERT INTO #t VALUES
(1, '2021-09-01', 2)
,(2, '2021-09-01', 3);
WITH cte AS(
SELECT ID, StartDate, NoOfMonths
FROM #t
UNION ALL
SELECT ID, DATEADD(MONTH, 1, StartDate), NoOfMonths-1
FROM cte
WHERE NoOfMonths > 1
)
SELECT ID, StartDate
FROM cte
ORDER BY ID, StartDate
This could be solved by having an additional calendar table, which would be populated and maintained by you. The content of the table could be just dates (first days of months). Then you would join records from that calendar table with your original table using DATEADD() function if it's MS SQL server. So something like:
select DateMonth
from CalendarTable ct
inner join YourTable yt
on ct.DateMonth between yt.StartDate and DATEADD (MONTH, yt.NoOfMonths, yt.StartDate)

How do I calculate amount of time in each week between two dates - SQL Server

[EDITED TO SIMPLIFY]
I have 500+ records. All of which have a reference number, a start date, an end date and a total machining time.
Ref StartDate EndDate MachineTimeHours
123 24/01/2020 30/01/2020 28
321 25/02/2020 27/02/2020 18
Starting at the start date, I need to calculate how many machining hours fall into 1 week and how many fall into the next.
Our working days are Monday to Thursday 8 Hours & Friday 4 Hours.
Ref 321 has a start of 25/2 which is a Tuesday and a finish date of 27/2 which is a Thursday in the same week. This will calculate as all 18 hours being in the same week.
Ref 123 has a start of 24/01. This is a Friday in Week 4 of 2020.
Based on my rules, that would be 4 hours in week 4 and 24 Hours in week 5.
I have a table called 'DatesList' which has all days on it (as well as week number and working hours).
I need my table to list each record for each week and I'll do the grouping on a separate report.
In effect I'd like
Ref StartDate EndDate MachineTimeHours Week Hours
123 24/01/2020 30/01/2020 28 4 4
123 24/01/2020 30/01/2020 28 5 24
321 25/02/2020 27/02/2020 18 9 18
You can start with creating some reference tables.
For the example those are just temporary tables.
Reference data:
--
-- Reference tables
--
CREATE TABLE #ref_calendar
(
CalDate DATE PRIMARY KEY,
DayOfWeek SMALLINT NOT NULL,
WeekNr SMALLINT NOT NULL,
IsHoliday BIT NOT NULL DEFAULT 0
);
DECLARE #year int = 2020;
SET DATEFIRST 1; -- 1: monday start
;WITH RCTE_DATES AS
(
SELECT
DATEFROMPARTS(#year, 1, 1) AS caldate
UNION ALL
SELECT dateadd(day, 1, caldate)
FROM RCTE_DATES
WHERE caldate <= DATEFROMPARTS(#year, 12, 31)
)
INSERT INTO #ref_calendar (CalDate, DayOfWeek, WeekNr)
SELECT
caldate,
DATEPART(weekday, caldate) AS DayOfWeek,
DATEPART(week, caldate) AS WeekNr
FROM rcte_dates c
WHERE NOT EXISTS
(
SELECT 1
FROM #ref_calendar ref
WHERE ref.CalDate = c.caldate
)
OPTION (MAXRECURSION 366);
CREATE TABLE #ref_workhours
(
Id INT IDENTITY(1,1) PRIMARY KEY,
DayOfWeek SMALLINT NOT NULL,
WorkHours DECIMAL(4,2) NOT NULL,
ActiveFrom DATE NOT NULL DEFAULT GetDate(),
ActiveTill DATE
);
INSERT INTO #ref_workhours
(DayOfWeek, WorkHours) VALUES
(1, 8.0), (2, 8.0), (3, 8.0), (4, 8.0), (5, 4.0),
(6, 0), (7, 0);
Some sample data:
--
-- Sample data
--
CREATE TABLE YourDateRangeTable
(
Id INT IDENTITY(1,1) PRIMARY KEY,
JobNumber INT NOT NULL,
PartNumber VARCHAR(8) NOT NULL,
Machine CHAR(3) NOT NULL,
StartDate DATE NOT NULL,
EndDate DATE NOT NULL
);
INSERT INTO YourDateRangeTable
(JobNumber, PartNumber, Machine, StartDate, EndDate) values
(12345, 'XYZ321', 'DL8', '2020-01-24', '2020-01-30');
Then you can run a query that uses the reference tables.
SELECT JobNumber, PartNumber, Machine
, YEAR(cal.CalDate) AS [Year]
, cal.WeekNr AS [Week]
, SUM(w.WorkHours) AS [Hours]
FROM YourDateRangeTable t
JOIN #ref_calendar cal
ON cal.CalDate >= t.StartDate
AND cal.CalDate < t.EndDate
JOIN #ref_workhours w
ON w.DayOfWeek = cal.DayOfWeek
GROUP BY JobNumber, PartNumber, Machine
, YEAR(cal.CalDate), cal.WeekNr;
Returns:
JobNumber PartNumber Machine Year Week Hours
12345 XYZ321 DL8 2020 4 4.00
12345 XYZ321 DL8 2020 5 24.00
A test on db<>fiddle here
You can get all the detes of two given date and also weeknumber and a case statement for the working hour. Based on the result from the inner query write an outer query which will give the sum of total working hour.
Here is the given query.
DECLARE #MinDate DATE = '20200124',
#MaxDate DATE = '20200130'
--Fri Week 4 = 4 hours
--Mon Week 5 = 8 hours
--Tue Week 5 = 8 hours
--Wed Week 5 = 8 hours
Select WeekNo, SUM(WorkingHour) as TotalWorkingHour from(
Select [DATE], DATEPART(WEEK, [DATE]) - DATEPART(WEEK, DATEADD(MM, DATEDIFF(MM,0,[DATE]), 0))+ 1 as WeekNo,
DATENAME(weekday, [DATE]) as WeekDay, Case DATENAME(weekday, [DATE])
when 'Friday' then 4
when 'Monday' then 8
when 'Tuesday' then 8
when 'Wednesday' then 8
else 0
end as WorkingHour from(
SELECT TOP (DATEDIFF(DAY, #MinDate, #MaxDate) + 1)
Date = DATEADD(DAY, ROW_NUMBER() OVER(ORDER BY a.object_id) - 1, #MinDate)
FROM sys.all_objects a
CROSS JOIN sys.all_objects b
)a
)b group by WeekNo
It will give the result as below:
WeekNo TotalWorkingHour
------------------------
4 4
5 24
You can find the demo Here.

#SQL - Order By matching record first

i need help to order this table (named "season") , by matching actual date with the BEGINDATE
ID NAME BEGINDATE
----------- -------------------- ----------
1 2014-2015 2014-10-01
2 2015-2016 2015-10-01
3 2016-2017 2016-10-01
4 2017-2018 2017-10-01
for example:
actual date is 2016/10/28 so we are in season 2016-2017 (id=3)
so the result should be
ID NAME BEGINDATE
----------- -------------------- ----------
3 2016-2017 2016-10-01
1 2014-2015 2014-10-01
2 2015-2016 2015-10-01
4 2017-2018 2017-10-01
UPDATE (SOLVED)
what i finally did was:
DECLARE #IDACTIVE AS INT = (SELECT MAX(ID) FROM SEASON WHERE BEGINDATE < GETDATE())
SELECT
1 AS ORDERBY,
ID,
NAME,
BEGINDATE
FROM SEASON
WHERE ID = #IDACTIVE
UNION
SELECT
2 AS ORDERBY,
ID,
NAME,
BEGINDATE
FROM SEASON
WHERE ID = #IDACTIVE
Follow the next approach:
1) Get The only matched row by using Top and Where clauses.
2) Get the all records except the one that you getting on point #1
3) Combine the result of two Selects via using UNION ALL.
Demo:-
Create table season (id int , NAME varchar(20),BEGINDATE date)
go
insert into season values (1,'2014-2015','2014-10-01')
insert into season values (2,'2015-2016','2015-10-01')
insert into season values (3,'2016-2017','2016-10-01')
insert into season values (4,'2017-2018','2017-10-01')
go
select * from (
select top 1 * from season
where BEGINDATE < getdate()
order by BEGINDATE desc
) a
union all
select * from season
where BEGINDATE != (
select top 1 BEGINDATE from season
where BEGINDATE < getdate()
order by BEGINDATE desc)
-- an another Soluation
select * from season
where DATEPART(Year,BEGINDATE) =DATEPART(Year,getdate())
union all
select * from season
where DATEPART(Year,BEGINDATE) !=DATEPART(Year,getdate())
The Result:
First move all future dates to the end, then order by beginDate
SELECT *
FROM season
ORDER BY CASE WHEN beginDate > GETDATE() THEN 0 ELSE 1 END,
beginDate
I think this is most easily done using window functions:
select s.*
from season s
order by (case when begindate = max(case when getdate() >= begindate then begindate end) over ()
then 1 else 2
end),
id

SQL - creating a list of custom dates between two dates

I am having trouble compiling a query than can do the following:
I have a table which has a startDate and endDate [tblPayments]
I have a column which stores a specific paymentDay [tblPayments]
Data
paymentID startDate endDate paymentDay
1 2016-01-01 2016-12-31 25
2 2015-06-01 2016-06-30 16
I am trying to generate a SELECT query which will split this specific table into separate lines based on the amount of months between these two dates, and set the paymentDay as the day for these queries
Example Output
paymentID expectedDate
1 2016-01-25
1 2016-02-25
1 2016-03-25
1 2016-04-25
1 2016-05-25
1 2016-06-25
1 2016-07-25
1 2016-08-25
1 2016-09-25
1 2016-10-25
1 2016-11-25
1 2016-12-25
2 2015-06-16
2 2015-07-16
2 2015-08-16
2 2015-09-16
2 2015-10-16
2 2015-11-16
2 2015-12-16
2 2016-01-16
2 2016-02-16
2 2016-03-16
2 2016-04-16
2 2016-05-16
I have found a query which will select the months between these dates but its adapting it to my table above, and multiple startDates and endDates I am struggling with
spliting the months
declare #start DATE = '2015-01-01'
declare #end DATE = '2015-12-31'
;with months (date)
AS
(
SELECT #start
UNION ALL
SELECT DATEADD(MM,1,date)
from months
where DATEADD(MM,1,date)<=#end
)
select Datename(MM,date) from months
This query is limited to just one startDate and endDate, so I haven't expanded it to change the DAY of the date.
Use a date table and a simple inner join
DECLARE #tblPayments table (paymentID int identity(1,1), startDate date, endDate date, paymentDay int)
INSERT #tblPayments VALUES
('2016-01-01', '2016-12-31', 25),
('2015-06-01', '2016-06-30', 16)
;WITH dates AS -- Build date within the range of startDate and endDate
(
SELECT MIN(startDate) AS Value, MAX(endDate) AS MaxDate FROM #tblPayments
UNION ALL
SELECT DATEADD(DAY, 1, Value), MaxDate
FROM dates WHERE DATEADD(DAY, 1, Value) <= MaxDate
)
SELECT pay.paymentID, dates.Value AS expectedDate
FROM
#tblPayments pay
INNER JOIN dates ON
dates.Value BETWEEN pay.startDate AND pay.endDate
AND DAY(dates.Value) = paymentDay
OPTION (maxrecursion 0)
I would create an in memory calendar table and then perform a simple query by joining to that:
-- Create a table with all the dates between the min and max dates in the
-- data table
DECLARE #Calendar TABLE
(
[CalendarDate] DATETIME
)
DECLARE #StartDate DATETIME
DECLARE #EndDate DATETIME
SELECT #StartDate = MIN(startdate), #EndDate = MAX(enddate) FROM YourDataTable
WHILE #StartDate <= #EndDate
BEGIN
INSERT INTO #Calendar (CalendarDate)
SELECT #StartDate
SET #StartDate = DATEADD(dd, 1, #StartDate)
END
-- Join to return only dates between the start and end date that match the Payment Day
SELECT D.PaymentId, C.CalendarDate FROM YourDataTable D
INNER JOIN #Calendar C ON C.CalendarDate BETWEEN D.StartDate AND D.EndDate
AND DATEPART(day, C.CalendarDate) = D.PaymentDay

Add Missing Date Range to Result Record Set

I have a table containing the working hours for the company. We define the range of the dates and the number of hours for the range.
The number of working hours which is not in the defined range is 9.5 hours.
I want to have the non-defined range with the value of 9.5 added to the result record set.
how should I make the query to get this result?
The table definition and added records:
IF OBJECT_ID ('dbo.tbl_WorkingHours') IS NOT NULL
DROP TABLE dbo.tbl_WorkingHours
GO
CREATE TABLE dbo.tbl_WorkingHours
(
Startdate DATETIME NOT NULL,
EndDate DATETIME NOT NULL,
HoursDefined FLOAT NULL,
Description VARCHAR (255) NULL,
PRIMARY KEY (Startdate,EndDate)
)
INSERT INTO dbo.tbl_WorkingHours
(Startdate,EndDate,HoursDefined,Description)
VALUES
('3/4/2010','3/29/2010',7,'')
INSERT INTO dbo.tbl_WorkingHours
(Startdate,EndDate,HoursDefined,Description)
VALUES
('5/4/2010','5/29/2010',8,'')
The Result of Select * :
Startdate | EndDate | HoursDefined | Description
----------------------------------------------------
3/4/2010 3/29/2010 7
5/4/2010 5/29/2010 8
My desired record set:
Startdate | EndDate | HoursDefined | Description
----------------------------------------------------
1/1/1900 3/3/2010 9.5
3/4/2010 3/29/2010 7
3/30/2010 5/3/2010 9.5
5/4/2010 5/29/2010 8
5/30/2010 1/1/2050 9.5
The below assumes it is not possible to have overlapping ranges or two defined ranges that are contiguous but held as separate rows.
WITH wh AS
(
SELECT Startdate, EndDate, HoursDefined, Description,
ROW_NUMBER() over (order by startdate) as rn
FROM tbl_WorkingHours
)
SELECT Startdate, EndDate, HoursDefined, Description
FROM wh
UNION ALL
SELECT ISNULL(dateadd(day,1,w1.EndDate),'19000101'),
ISNULL(dateadd(day,-1,w2.StartDate),'20500101') , 9.5 AS HoursDefined,''
FROM wh w1 FULL OUTER JOIN wh w2
ON w2.rn = w1.rn+1
ORDER BY Startdate
try something like this:
DECLARE #tbl_WorkingHours table (Startdate DATETIME NOT NULL
,EndDate DATETIME NOT NULL
,HoursDefined FLOAT NULL
,Description VARCHAR (255) NULL
,PRIMARY KEY (Startdate,EndDate)
)
INSERT INTO #tbl_WorkingHours (Startdate,EndDate,HoursDefined,Description) VALUES ('3/4/2010','3/29/2010',7,'')
INSERT INTO #tbl_WorkingHours (Startdate,EndDate,HoursDefined,Description) VALUES ('5/4/2010','5/29/2010',8,'')
;WITH OrderedRows AS
( SELECT
Startdate,EndDate,HoursDefined,Description, ROW_NUMBER() OVER (ORDER BY Startdate,EndDate) AS RowNumber
FROM #tbl_WorkingHours
)
SELECT --before rows
CONVERT(datetime,'1/1/1900') AS Startdate,ISNULL(MIN(Startdate),CONVERT(datetime,'1/2/2050'))-1 AS EndDate,9.5 AS HoursDefined, CONVERT(VARCHAR (255),'') AS Description
FROM #tbl_WorkingHours
UNION ALL
SELECT --actual rows
Startdate,EndDate,HoursDefined,Description
FROM #tbl_WorkingHours
UNION ALL
SELECT --between rows
a.EndDate+1,b.Startdate-1,9.5,''
FROM OrderedRows a
INNER JOIN OrderedRows b ON a.RowNumber=b.RowNumber-1
UNION ALL
SELECT --after rows
ISNULL(MAX(EndDate),CONVERT(datetime,'1/1/2050')) AS Startdate,CONVERT(datetime,'1/2/2050')-1 AS EndDate,9.5 AS HoursDefined, CONVERT(VARCHAR (255),'') AS Description
FROM #tbl_WorkingHours
ORDER BY Startdate,EndDate
OUTPUT:
Startdate EndDate HoursDefined Description
----------------------- ----------------------- ---------------------- -----------
1900-01-01 00:00:00.000 2010-03-03 00:00:00.000 9.5
2010-03-04 00:00:00.000 2010-03-29 00:00:00.000 7
2010-03-30 00:00:00.000 2010-05-03 00:00:00.000 9.5
2010-05-04 00:00:00.000 2010-05-29 00:00:00.000 8
2010-05-29 00:00:00.000 2050-01-01 00:00:00.000 9.5
(5 row(s) affected)