I have checked Temp_Calc_1 against Temp_Calc_2 and they both have the same column datatypes (float, nvarchar(255)) and are in the same order when reading down the table. When I try to run this on the empty Temp_Calc_2, I get an error:
Error converting nvarchar to float
on the line INSERT INTO dbo.Temp_Calc_2
USE MfgMetrics
INSERT INTO dbo.Temp_Calc_2
SELECT
zps.[Plant], [Work Center],
[Scheduled start Date], [SCHEDULE START TIME],
[SCHEDULED FINISHED DATE], [SCHEDULED FINISHED TIME],
[MATERIAL NUMBER], [MATERIAL DESCRIPTON],
[ORDER NUMBER], [ORDER TYPE],
[PLANNED QUANTITY], [PLANNED QTY - PROD UN],
[DELIVERED QTY], [DELIVERED QTY - PROD UN],
[RemainingQty(BUn)], [REMAINING QTY - Prod Un],
[COMMITED QTY], [COMMITED QTY - PROD UN], [UOM],
[STORAGE LOCATION], [COMMENTS],
[RATE QUANTITY], [RATE QUANTITY - PROD UN], [RATE HOUR],
[OPERATING EFFIECIENCY], [UNIT],
[STD UNITS / HR], [STD UNITS / HR - PROD UN], [UOM2],
[ORDER STATUS], [ACTUAL START DATE], [ACTUAL START TIME],
[MRP CONTROLLER], [CREATED ON], [TIME CREATED],
[CHANGED ON], [TIME CHANGE],
[ORDER TEXT LINES], [ORDER TEXT 2nd LINE], [FileDate],
scf.[OQ_RxnTime_(mins)], scf.[RunDurThreshold_(hrs)],
CASE
WHEN (zps.[MATERIAL NUMBER] LIKE '%.%')
THEN zps.[MATERIAL NUMBER]
WHEN ISNUMERIC(zps.[MATERIAL NUMBER]) = 1
THEN CAST(CAST(zps.[MATERIAL NUMBER] AS INT) AS NVARCHAR(255))
ELSE zps.[MATERIAL NUMBER]
END As [Material],
(CAST(CAST(zps.[ORDER NUMBER] AS INT) AS NVARCHAR(255)) + '_' + CAST(CAST(zps.[PLANNED QUANTITY] AS INT) AS NVARCHAR(255))) AS Order_Quantity,
scf.[OQ_RxnTime_(mins)] * zps.[STD UNITS / HR] / 60 AS OQWindow
FROM
Temp_Calc_1 zps
INNER JOIN
SAWorkCenters swc ON zps.Plant = swc.Plant
AND zps.[Work Center] = swc.WCGroup
INNER JOIN
SchedAttCalcFactors scf ON zps.Plant = scf.[Plant Code]
ORDER BY
zps.Plant, zps.[Work Center], zps.[ORDER NUMBER], zps.FileDate
GO
Related
Is there a way in which I can insert data from one table into another when today is Monday?
I tried making something like the below, using CASE WHEN, however it doesn't quite work right, any help would be welcomed
INSERT INTO [dbo].[WF_All]
SELECT (CASE WHEN (DATENAME(WEEKDAY,FLOOR(convert(float,getdate()))))='MONDAY' THEN
(
SELECT [Parent Number]
,[Parent Name]
,[Customer Number]
,[Customer Name]
,[Collector]
,[Outstanding]
FROM dbo.[Invoices]
)
ELSE NULL END )
yes , like this :
INSERT INTO [dbo].[WF_All]
SELECT [Parent Number]
,[Parent Name]
,[Customer Number]
,[Customer Name]
,[Collector]
,[Outstanding]
FROM dbo.[Invoices]
WHERE DATENAME(WEEKDAY,GETDATE()) = 'Monday'
or
... WHERE DATEPART(WEEKDAY, GETDATE()) = 2 --Monday
Is this what you want.
if datename(weekday,getdate()) = 'MONDAY' then
INSERT INTO [dbo].[WF_All] (
-- column names go here
)
SELECT [Parent Number]
,[Parent Name]
,[Customer Number]
,[Customer Name]
,[Collector]
,[Outstanding]
FROM dbo.[Invoices]
How can I use Sum, Cast and Partition by functions together?
I get error.
Conversion failed when converting the nvarchar value '693.41' to data
type int."
I tried this
SUM(CAST([total price] AS INT)) OVER (PARTITION BY (ProjectType)) as TotalPriceV2
Full query is at the below.
SELECT
ID,
[Project Manager],
Job#,
[Date],
[Job Type],
first_value([Job Name]) OVER (PARTITION BY value_partition ORDER BY ID) CustomerGroup, Value_Partition
Customer,
[Sales Rep1],
DeliveryType,
ProjectType,
[Item Price],
[Service Price],
[Total Price],
SUM(CAST([total price] AS INT)) OVER (PARTITION BY (ProjectType)) as TotalPriceV2
FROM (
SELECT
ID,
[Project Manager], Job#, [Date], [Job Type], [Job Name],Customer,[Sales Rep1],DeliveryType,ProjectType,[Item Price],[Service Price],[Total Price],
SUM(CASE WHEN [JOB NAME] IS NULL THEN 0 ELSE 1 END) OVER (ORDER BY ID) AS Value_Partition
FROM Testing2
WHERE
[Date] IS NOT NULL AND
([Date] NOT LIKE '0' OR JOB# NOT LIKE '0' OR [JOB TYPE] NOT LIKE '0')
AND [Project Manager] NOT LIKE 'ITEM / SERVICE'
) AS X
First, identify the rows that have problems. You are converting to an int, so:
select price
from Testing2
where try_convert(int, price) is null and price is not null;
At least some of the values will have decimal points (as in your example). To see if this is the only problem, I would suggest converting to a decimal next:
select price
from Testing2
where try_convert(decimal(20, 4), price) is null and price is not null;
If this returns nothing, you are set. If not, you will need to figure out how to address these exceptions.
Then, I would phrase the calculation using decimals and not floats:
SUM(TRY_CAST([total price] AS DECIMAL(20, 4))) OVER (PARTITION BY (ProjectType)) as TotalPriceV2
Monetary amounts should generally be represented using fixed-point values rather than approximate floating point values. The issue with floating point values is that information may be lost. Consider this example with reals:
select cast(1000000 as real) + cast(0.01 as real),
cast(1000000 as decimal(20, 4)) + cast(0.01 as decimal(20, 4))
Integer will not have decimal values, and it will throw an error.
If I use this, similar to the example you have.
Declare #val nvarchar(10) = '10.24'
select cast (#val as int)
I get this following error.
Msg 245, Level 16, State 1, Line 3
Conversion failed when converting the nvarchar value '10.24' to data type int.
Now to avoid this error, I can round the digit to 0 decimal places and convert as Int. Also, I would recommend to use Try_Cast to avoid any cases of actual nvarchar values(it would convert it to null) if you are using sql server 2012 or more.
Declare #val nvarchar(10) = '10.24'
select Try_cast (round(#val,0) as int) as valuen
Output, I think this will work in your sum function.
valuen
10
Why don't you cast it in inner query with decimal(16,9) instead of int
SELECT
ID,
[Project Manager],
Job#,
[Date],
[Job Type],
first_value([Job Name]) OVER (PARTITION BY value_partition ORDER BY ID) CustomerGroup, Value_Partition
Customer,
[Sales Rep1],
DeliveryType,
ProjectType,
[Item Price],
[Service Price],
[Total Price],
SUM([total price]) OVER (PARTITION BY (ProjectType)) as TotalPriceV2
FROM (
SELECT
ID,
[Project Manager], Job#, [Date], [Job Type], [Job Name],Customer,[Sales Rep1],DeliveryType,ProjectType,[Item Price],[Service Price],cast([Total Price] as decimal(16,9)) as [Total Price],
SUM(CASE WHEN [JOB NAME] IS NULL THEN 0 ELSE 1 END) OVER (ORDER BY ID) AS Value_Partition
FROM Testing2
WHERE
[Date] IS NOT NULL AND
([Date] NOT LIKE '0' OR JOB# NOT LIKE '0' OR [JOB TYPE] NOT LIKE '0')
AND [Project Manager] NOT LIKE 'ITEM / SERVICE'
) AS X
If you have a combination of string and number as your column value and you want to sum up the number. For SQL Server 2012+ you can use TRY_CAST or TRY_CONVERT to avoid any casting errors.
TRY_CAST (Transact-SQL)
In your scenario, you are not using proper data type for casting, you have values like 693.41 which can't be casted to INT, instead you should use DECIMAL datatype.
One more suggestion, instead of using NOT LIKE, better use <> in SQL Server like following.
Change
([Date] NOT LIKE '0' OR JOB# NOT LIKE '0' OR [JOB TYPE] NOT LIKE '0')
to
([Date] <> '0' OR JOB# <> '0' OR [JOB TYPE] <> '0')
One possible solution is to firstly convert the nvarchar value to decimal and then to integer:
CAST(CAST([total price] AS FLOAT) AS INT)
However, in this way the decimal part is lost if it matters to you.
I have this SQL table that looks like this
As you can see the Original Principal Balance is not ordered correctly. These variables are stored as a VARCHAR. How would I sort and order them correctly?
Here is my sql code:
WITH Original_Principal_Bal
AS (
SELECT [New Loan Number]
,[Current Amortizing UPB]
,[Current Def UPB]
,sum([Current Amortizing UPB] + [Current Def UPB]) OVER (PARTITION BY Deal) AS [Total UPB]
,BPO
,[Current Rate]
,[Current Maturity]
,[Next Due Date]
,[First Payment Date]
,CASE
WHEN [Original Loan Amount] BETWEEN 0.01
AND 100000
THEN '$0.01 to $100,000'
WHEN [Original Loan Amount] BETWEEN 100000.01
AND 200000
THEN '$100,000.01 to $200,000'
WHEN [Original Loan Amount] BETWEEN 200000.01
AND 300000
THEN '$200,000.01 to $300,000'
WHEN [Original Loan Amount] BETWEEN 300000.01
AND 400000
THEN '$300,000.01 to $400,000'
WHEN [Original Loan Amount] BETWEEN 400000.01
AND 500000
THEN '$400,000.01 to $500,000'
WHEN [Original Loan Amount] BETWEEN 500000.01
AND 600000
THEN '$500,000.01 to $600,000'
WHEN [Original Loan Amount] BETWEEN 600000.01
AND 700000
THEN '$600,000.01 to $700,000'
WHEN [Original Loan Amount] BETWEEN 700000.01
AND 800000
THEN '$700,000.01 to $800,000'
WHEN [Original Loan Amount] BETWEEN 800000.01
AND 900000
THEN '$800,000.01 to $900,000'
WHEN [Original Loan Amount] BETWEEN 900000.01
AND 1000000
THEN '$900,000.01 to $1,000,000'
WHEN [Original Loan Amount] BETWEEN 1100000.01
AND 1200000
THEN '$1,100,000.01 to $1,200,000'
WHEN [Original Loan Amount] BETWEEN 1300000.01
AND 1400000
THEN '$1,300,000.01 to $1,400,000'
WHEN [Original Loan Amount] BETWEEN 1600000.01
AND 1700000
THEN '$1,600,000.01 to $1,700,000'
WHEN [Original Loan Amount] BETWEEN 1900000.01
AND 2000000
THEN '$1,900,000.01 to $2,000,000'
WHEN [Original Loan Amount] > 2000000.01
THEN '$2,000,000 or greater'
END AS [Original Principal Balance]
FROM Portfolio_Analytics..Securitization_Tape
)
SELECT [Original Principal Balance]
,COUNT([New Loan Number]) AS [Number of Mortgage Loans]
,ROUND(sum([Current Amortizing UPB] + [Current Def UPB]), 0) AS [Aggregate Unpaid Principal Balance as of Cut-off Date ($)]
,ROUND(avg([Current Amortizing UPB] + [Current Def UPB]), 0) AS [Average Unpaid Principal Balance ($)]
,ROUND(sum(([Current Amortizing UPB] + [Current Def UPB]) / [Total UPB]) * 100, 2) AS [Percetage of Aggregate Principal Balance as of Cut-off Date(%)]
,sum(BPO) AS [Aggregate Updated Value($)]
,ROUND(sum([Current Rate] * ([Current Amortizing UPB] + [Current Def UPB])) / sum([Current Amortizing UPB] + [Current Def UPB]), 2) AS [Weighted Average Mortgage Interest Rate(%)]
,ROUND(sum(([Current Amortizing UPB] + [Current Def UPB]) / bpo * ([Current Amortizing UPB] + [Current Def UPB])) / sum([Current Amortizing UPB] + [Current Def UPB]) * 100, 2) AS [Weighted Average Updated Loan-to-Value Ratio(%)]
,ROUND(sum((DATEDIFF(month, [Next Due Date], [Current Maturity]) + 1) * ([Current Amortizing UPB] + [Current Def UPB])) / (sum([Current Amortizing UPB] + [Current Def UPB])), 0) AS [Weighted Average Remaining Term to Maturity(Months)]
,ROUND(sum((DATEDIFF(month, [First Payment Date], [Next Due Date]) + 1) * ([Current Amortizing UPB] + [Current Def UPB])) / (sum([Current Amortizing UPB] + [Current Def UPB])), 0) AS [Weighted Average Remaining Term to Maturity(Months)]
FROM Original_Principal_Bal
GROUP BY [Original Principal Balance]
Perhaps I need to store the numbers differenly when I create the table, I am not sure how else to match what I want it to look like though.
You can do:
ORDER BY MIN([Original Loan Amount])
You will also need to include [Original Loan Amount] in the CTE.
As trincot commented, "rendering" doesn't belong in the database layer. I don't necesarily agree or disagree with this statement. While it may be a "best practice" there are always practical reasons to go against the norm.
Seeing as your bucket labels are manually entered strings, I think the best option would be to simply add a ranking column to your select statement. Something like this:
WITH Original_Principal_Bal
AS (
SELECT [New Loan Number]
,[Current Amortizing UPB]
,[Current Def UPB]
,sum([Current Amortizing UPB] + [Current Def UPB]) OVER (PARTITION BY Deal) AS [Total UPB]
,BPO
,[Current Rate]
,[Current Maturity]
,[Next Due Date]
,[First Payment Date]
,CASE
WHEN [Original Loan Amount] BETWEEN 0.01
AND 100000
THEN '$0.01 to $100,000'
WHEN [Original Loan Amount] BETWEEN 100000.01
AND 200000
THEN '$100,000.01 to $200,000'
WHEN [Original Loan Amount] BETWEEN 200000.01
AND 300000
THEN '$200,000.01 to $300,000'
WHEN [Original Loan Amount] BETWEEN 300000.01
AND 400000
THEN '$300,000.01 to $400,000'
WHEN [Original Loan Amount] BETWEEN 400000.01
AND 500000
THEN '$400,000.01 to $500,000'
WHEN [Original Loan Amount] BETWEEN 500000.01
AND 600000
THEN '$500,000.01 to $600,000'
WHEN [Original Loan Amount] BETWEEN 600000.01
AND 700000
THEN '$600,000.01 to $700,000'
WHEN [Original Loan Amount] BETWEEN 700000.01
AND 800000
THEN '$700,000.01 to $800,000'
WHEN [Original Loan Amount] BETWEEN 800000.01
AND 900000
THEN '$800,000.01 to $900,000'
WHEN [Original Loan Amount] BETWEEN 900000.01
AND 1000000
THEN '$900,000.01 to $1,000,000'
WHEN [Original Loan Amount] BETWEEN 1100000.01
AND 1200000
THEN '$1,100,000.01 to $1,200,000'
WHEN [Original Loan Amount] BETWEEN 1300000.01
AND 1400000
THEN '$1,300,000.01 to $1,400,000'
WHEN [Original Loan Amount] BETWEEN 1600000.01
AND 1700000
THEN '$1,600,000.01 to $1,700,000'
WHEN [Original Loan Amount] BETWEEN 1900000.01
AND 2000000
THEN '$1,900,000.01 to $2,000,000'
WHEN [Original Loan Amount] > 2000000.01
THEN '$2,000,000 or greater'
END AS [Original Principal Balance]
,CASE
WHEN [Original Loan Amount] BETWEEN 0.01
AND 100000
THEN 0
WHEN [Original Loan Amount] BETWEEN 100000.01
AND 200000
THEN 1
WHEN [Original Loan Amount] BETWEEN 200000.01
AND 300000
THEN 2
WHEN [Original Loan Amount] BETWEEN 300000.01
AND 400000
THEN 4
WHEN [Original Loan Amount] BETWEEN 400000.01
AND 500000
THEN 5
WHEN [Original Loan Amount] BETWEEN 500000.01
AND 600000
THEN 6
WHEN [Original Loan Amount] BETWEEN 600000.01
AND 700000
THEN 7
WHEN [Original Loan Amount] BETWEEN 700000.01
AND 800000
THEN 8
WHEN [Original Loan Amount] BETWEEN 800000.01
AND 900000
THEN 9
WHEN [Original Loan Amount] BETWEEN 900000.01
AND 1000000
THEN 10
WHEN [Original Loan Amount] BETWEEN 1100000.01
AND 1200000
THEN 11
WHEN [Original Loan Amount] BETWEEN 1300000.01
AND 1400000
THEN 12
WHEN [Original Loan Amount] BETWEEN 1600000.01
AND 1700000
THEN 13
WHEN [Original Loan Amount] BETWEEN 1900000.01
AND 2000000
THEN 14
WHEN [Original Loan Amount] > 2000000.01
THEN 15
END AS [Balance Rank]
FROM Portfolio_Analytics..Securitization_Tape
)
SELECT [Original Principal Balance]
,COUNT([New Loan Number]) AS [Number of Mortgage Loans]
,ROUND(sum([Current Amortizing UPB] + [Current Def UPB]), 0) AS [Aggregate Unpaid Principal Balance as of Cut-off Date ($)]
,ROUND(avg([Current Amortizing UPB] + [Current Def UPB]), 0) AS [Average Unpaid Principal Balance ($)]
,ROUND(sum(([Current Amortizing UPB] + [Current Def UPB]) / [Total UPB]) * 100, 2) AS [Percetage of Aggregate Principal Balance as of Cut-off Date(%)]
,sum(BPO) AS [Aggregate Updated Value($)]
,ROUND(sum([Current Rate] * ([Current Amortizing UPB] + [Current Def UPB])) / sum([Current Amortizing UPB] + [Current Def UPB]), 2) AS [Weighted Average Mortgage Interest Rate(%)]
,ROUND(sum(([Current Amortizing UPB] + [Current Def UPB]) / bpo * ([Current Amortizing UPB] + [Current Def UPB])) / sum([Current Amortizing UPB] + [Current Def UPB]) * 100, 2) AS [Weighted Average Updated Loan-to-Value Ratio(%)]
,ROUND(sum((DATEDIFF(month, [Next Due Date], [Current Maturity]) + 1) * ([Current Amortizing UPB] + [Current Def UPB])) / (sum([Current Amortizing UPB] + [Current Def UPB])), 0) AS [Weighted Average Remaining Term to Maturity(Months)]
,ROUND(sum((DATEDIFF(month, [First Payment Date], [Next Due Date]) + 1) * ([Current Amortizing UPB] + [Current Def UPB])) / (sum([Current Amortizing UPB] + [Current Def UPB])), 0) AS [Weighted Average Remaining Term to Maturity(Months)]
FROM Original_Principal_Bal
GROUP BY [Original Principal Balance]
try:
order by cast(substring(left( [Original Principal Balance],charindex(' ',[Original Principal Balance])-1),2,1000) as decimal(18,4))
This will convert the first number to a number and sort on that.
There's one very cool thing about the MONEY data type... It doesn't complain about commas or currency symbols and it's a numeric data type, so it sorts like and other number... Here are few examples...
DECLARE #string VARCHAR(50) = '$700,000.01 to $800,000';
SELECT CONVERT(MONEY, SUBSTRING(#string, 1, CHARINDEX(' ', #string, 2)));
SELECT CONVERT(MONEY, LEFT(#string, PATINDEX('%[^0-9.,$]%', #string)));
SELECT CONVERT(MONEY, LEFT(#string, CHARINDEX(' ', #string)));
I'm using Microsoft SQL Server and have 2 tables, AbsenceHistory and FITNoteHistory.
AbsenceHistory:
[Employee Number], [Absence Number], [Start Date], [End Date]
FITNoteHistory:
[Absence Number], [FIT Note Number], [Start Date], [End Date]
I need to identify where there is a gap in the FIT Note History, that doesn't cover the entire Absence Period between DateAdd(d,7,AbsenceHistory.[Start Date]) and AbsenceHistory.[End Date], where AbsenceHistory.[End Date] is not null and DATEDIFF(d,AbsenceHistory.[Start Date],AbsenceHistory.[End Date]) >= 7.
The output needs to give me the actual date gaps for each absence.
E.g. Absence Number, Date of Gap
Can anyone help?
Example Data:
AbsenceHistory:
[Employee Number], [Absence Number], [Start Date], [End Date]
18615, 70, '01-Jan-2018', '31-Jan-2018'
FITNoteHistory:
[Absence Number], [FIT Note Number], [Start Date], [End Date]
70, 1, '08-Jan-2018', '15-Jan-2018'
70, 15, '18-Jan-2018', '24-Jan-2018'
70, 31, '26-Jan-2018', '01-Feb-2018'
My expected output would be:
[Employee Number], [Absence Number], [Gap Date]
18615, 70, '16-Jan-2018'
18615, 70, '17-Jan-2018'
18615, 70, '25-Jan-2018'
This should get you started
declare #t table ([Absence Number] int, [FIT Note Number] int, [Start Date] date, [End Date] date)
insert into #t values
(70, 1, '08-Jan-2018', '15-Jan-2018')
, (70, 15, '18-Jan-2018', '24-Jan-2018')
, (70, 31, '26-Jan-2018', '01-Feb-2018');
select t.[Absence Number], t.[FIT Note Number], t.[Start Date], t.[End Date]
from #t t
order by t.[Start Date], t.[End Date], t.[FIT Note Number];
declare #minDate date = (select min([End Date]) from #t);
declare #maxDate date = (select max([Start Date]) from #t);
with cteDate as
(
select #minDate as dDate
union all
select cast(dateadd(dd, 1, dDate) as date)
from cteDate
where dDate < #maxDate
)
, cteNext as
( select t.[Absence Number], t.[FIT Note Number], t.[Start Date], t.[End Date]
, lead(t.[Start Date], 1) OVER (ORDER BY t.[Start Date]) AS nextStart
from #t t
)
select n.[Absence Number], n.[FIT Note Number], n.[Start Date], n.[End Date]
, d.dDate
from cteNext n
join cteDate d
on d.dDate > n.[End Date]
and d.dDate < n.nextStart
order by d.dDate;
I have a table and query as follow:
I am trying to get overlapping records between [Assignment Start Date] and [Assignment End Date] for same Employee Id.
In short I need data for those Employee Id which are allocated for same time period or overlapping time period from below example.
e.g.
[Employee Id] [Assignment Start Date] [Assignment End Date] [Allocation Percentage]
100 2016-03-01 2017-02-28 100
102 2016-06-01 2016-12-31 100
102 2016-07-01 2016-10-30 100
102 2016-11-01 2017-01-31 100
103 2017-02-01 2017-05-30 100
102 2017-04-01 2017-06-30 100
102 2017-11-01 2017-01-31 100
104 2017-02-01 2017-05-01 100
CREATE TABLE #Result
(
PK INT IDENTITY(1,1),
[BU] VARCHAR(20),
[Division] VARCHAR(20),
[Product Name] VARCHAR(30),
[Employee ID] NVARCHAR(20),
[Resource Name] VARCHAR(50),
[Resource_ID] INT,
[Assignment Start Date] DATE,
[Assignment End Date] DATE,
[Allocation Percentage] INT,
[Location] VARCHAR(100),
[Development Manager] VARCHAR(50),
[Allocation] VARCHAR(20)
);
SELECT DISTINCT r1.PK, r1.Resource_ID,r1.[Employee ID], r1.[Assignment Start Date] AS 'Start 1' ,r1.[Assignment End Date] AS 'End 1' , r2.[Assignment Start Date] , r2.[Assignment End Date]
INTO #temp1
FROM #Result r1
INNER JOIN #Result r2
ON r1.[Employee ID] = r2.[Employee ID]
AND (r1.PK <> r2.PK)
AND ((r1.[Assignment Start Date] <= r2.[Assignment Start Date]) AND (r1.[Assignment End Date] >= r2.[Assignment Start Date]))
OR ((r1.[Assignment Start Date] > r2.[Assignment Start Date] AND r1.[Assignment Start Date] <= r2.[Assignment End Date]) AND (r1.[Assignment End Date] <= r2.[Assignment End Date]))
OR ((r1.[Assignment Start Date] > r2.[Assignment Start Date] AND r1.[Assignment Start Date] <= r2.[Assignment End Date]) AND (r1.[Assignment End Date] > r2.[Assignment End Date]))
OR (r1.[Assignment Start Date] = r2.[Assignment End Date])
I have tried using above query but it gives all records related to overlapping employee even if that entry for that employee is not overlapping.
In above example there is a Employee Id 102 which has 2 overlapping entries and 3rd entry which is not overlapping I want to remove it from this result. please help.
CTE, row_number and a self join
with CTE as
(
select PK, Resource_ID, [Employee ID] as Emp_ID, [Assignment Start Date] as s_Date, [Assignment End Date] as e_date,
row_number() over(partition by [Employee ID] order by [Assignment Start Date] ) as rn
from #Result
)
select t1.*, t2.*
from CTE t1
inner join CTE t2
on t1.Resource_ID = t2.Resource_ID
and t1.Emp_ID = t2.Emp_ID
and t2.rn = t1.rn +1
where t2.s_date <= t1.e_date
or t1.e_date is null -- allows for null end date
Your SQL query should look like that below:
SELECT DISTINCT r1.PK, r1.Resource_ID,r1.[Employee ID], r1.[Assignment Start Date] AS 'Start 1' ,r1.[Assignment End Date] AS 'End 1' , r2.[Assignment Start Date] , r2.[Assignment End Date]
INTO #temp1
FROM #Result r1
JOIN #Result r2 on r1.[Employee ID] = r2.[Employee ID]
WHERE (
(r2.[Assignment Start Date] BETWEEN r1.[Assignment Start Date] and r1.[Assignment End Date])
or
(r2.[Assignment End Date] between p1.[Assignment Start Date] and p1.[Assignment End Date])
)
AND r1.PK <> r2.PK