SELECT DISTINCT FROM 3 columns with all the records - sql

I would like to query and get for all the records with the same datetime ,filter by Type , Provider and Operator.
If I run select distinct EventStamp I get all the records that I need, but I miss the type , provider and operator.
Like the screenshots if I have the Type OPR I need this record
If all the types are DDE I need Provider RDSSERVER\Intouch.
SELECT [EventStamp] ,[TagName] ,[Description],[Area] ,[Type],[Value], Antes FROM
(
SELECT distinct [EventStamp]
,[TagName]
,[Description]
,[Area]
,[Type]
,[Value]
,[CheckValue] as Antes
FROM [dbo].[v_EventHistory] where type = 'OPR'
UNION
SELECT distinct [EventStamp]
,[TagName]
,[Description]
,[Area]
,[Type]
,[Value]
,[CheckValue] as Antes
FROM [dbo].[v_EventHistory] where type = 'DDE'
)as EV order by EventStamp desc
With this code I miss the type , provider and operator.
I nee like this
Shared query from Hannover (Thank you)

It sounds like you need to use IN to identify all the records with the same Event Stamp, Provider and Operator.
SELECT *
FROM [dbo].[v_EventHistory]
WHERE CAST([EventStamp] AS VARCHAR(25)) + [Provider] + [Operator]
IN ( SELECT DISTINCT CAST([EventStamp] AS VARCHAR(25)) + [Provider] + [Operator]
FROM [dbo].[v_EventHistory]
WHERE [type] IN ( 'OPR', 'DDE' )
)
ORDER BY EventStamp DESC

Related

How to Build select Query split Temp Value to two column one Per Number And Another to Text when Flag Allow 1?

I work on a query for SQL Server 2012. I have an issue: I can't build select
Query split Column Temp value to two Column When row in the temp table #nonparametric has the flag Allow = 1,
it must split column Temp value from #nonparametric to two column when the flag Allow = 1 .
suppose column Temp value has value 50.40 kg it must split to two column
First column with number so it will have 50.40 and it will be same Name as Parametric .
Second column with Text so it will have kg and it will be same Name as Parametric + 'Units'.
meaning Name will be ParametricUnit .
I need to build query that split this on two column when Flag Allow =1 .
create table #nonparametricdata
(
PART_ID nvarchar(50) ,
CompanyName nvarchar(50),
PartNumber nvarchar(50),
DKFeatureName nvarchar(100),
Tempvalue nvarchar(50),
FlagAllow bit
)
insert into #nonparametricdata
values
('1222','Honda','silicon','package','15.50Am',0),
('1900','MERCEIS','GLASS','family','90.00Am',1),--Build select query split data because FlagAllow=1
('5000','TOYOTA','alominia','source','70.20kg',0),
('8000','MACDA','motor','parametric','50.40kg',1),----Build select query split data because FlagAllow=1
('8900','JEB','mirror','noparametric','75.35kg',0)
create table #FinalTable
(
DKFeatureName nvarchar(50),
DisplayOrder int
)
insert into #FinalTable (DKFeatureName,DisplayOrder)
values
('package',3),
('family',4),
('source',5),
('parametric',2),
('noparametric',1)
what I try is below :
DECLARE #SelectqueryData NVARCHAR(MAX)
SELECT
#SelectqueryData = STUFF(
(
SELECT ', ' + case when B.FlagAllow = 1 then '['+A.DKFeatureName+'],['+A.DKFeatureName+'Unit]' else quotename(A.DKFeatureName) end
FROM #FinalTable A
join (Select distinct DKFeatureName,FlagAllow
From #nonparametricdata
) B on A.DKFeatureName=B.DKFeatureName
ORDER BY DisplayOrder
FOR XML PATH ('')
),1,2,''
)
select #SelectqueryData
--select #SelectqueryData from table
Expected Result is :
[noparametric], [parametric]--QueryGetNumber,[parametricUnit]--QueryGetUnitOfMeasure
, [package], [family]--QueryGetNumber,[familyUnit]--QueryGetUnitOfMeasure, [source]
when make query above it must give me result as image(for Explain Only) :
You're looking for a DYNAMIC PIVOT
Example
DECLARE #SelectqueryData NVARCHAR(MAX)
SELECT #SelectqueryData = STUFF( (
SELECT ', ' + case when B.FlagAllow = 1 then '['+A.DKFeatureName+'],['+A.DKFeatureName+'Unit]' else quotename(A.DKFeatureName) end
FROM #FinalTable A
join (Select distinct DKFeatureName,FlagAllow
From #nonparametricdata
) B on A.DKFeatureName=B.DKFeatureName
ORDER BY DisplayOrder
FOR XML PATH ('')
),1,2,''
)
Declare #SQL varchar(max) = '
Select *
From (
Select A.Part_ID
,A.PartNumber
,A.CompanyName
,B.*
From #nonparametricdata A
Cross Apply ( values ( DKFeatureName ,case when FlagAllow=1 then left(TempValue,patindex(''%[A-Z]%'',TempValue+''A'')-1) else TempValue end )
,( DKFeatureName+''Unit'',case when FlagAllow=1 then substring(TempValue,patindex(''%[A-Z]%'',TempValue+''A''),10) else null end )
) B(Item,Value)
) src
Pivot (max(value) for Item in ('+#SelectqueryData+') ) pvt
'
--Print #SQL
Exec(#SQL)
Returns

Pivot with dates of given month

I am working with a view I'm trying to process and present in a more usable way using SQL Server.
The data:
select *
from vReportData
where date between '01.01.2020' and '31.01.2020'
which looks like this:
persnr date abw target attendance
----------------------------------------------------
000001 2020-01-01 5.00 4.45
000001 2020-01-02 0.00 8.00
000001 2020-01-04 6.00 7.00
000001 2020-01-30 6.00 6.00
000001 2020-01-31 6.00 6.50
[...]
999999 2020-01-02 U 5.00 0.00
999999 2020-01-30 4.00 5.00
999999 2020-01-31 5.00 5.00
The desired output:
persnr 01.01.2020 02.01.2020 [...] 30.01.2020 31.01.2020 sum
-----------------------------------------------------------------------
000001 4.45/5.00 8.00/0.00 [...] 6.00/6.00 6.50/6.00 xxx
999999 U [...] 5.00/4.00 0.00/5.00 xxx
Basically I would like to transform the table to have one line per person and have the dates as column. As for the abw, target and attendance I want to get them to be displayed by the date it happened.
The idea
I'm very likely need to use pivot function to get the table shape I want. Since I don't have all dates of a given month in my vReportData I thought about generating them first using something along the lines of:
declare #start datetime = '2020-05-01'
declare #ende datetime = '2020-05-31'
;with calender AS
(
select #start as Datum
union all
select Datum + 1 from Calender
where Datum + 1 <= #ende
)
select [Date] = convert(varchar, Datum, 104), 0.00 as value
from calender
to get the dates of the given month as rows.
Adding the persnr I ended up with:
select distinct
#vReportData.persnr,
[Date] = convert(varchar, Datum, 104)
from
calender
cross join
#vReportData
I don't how how to get the pivot working using my approach.
My complete SQL + attempt can be found here - for testing purpose I ended up changing the end date at some point.
https://data.stackexchange.com/stackoverflow/query/1240742/reportdata
additon & followup:
I was trying a few other attemts. Here's another issue I encountered:
I ended up using a dynamic pivot where I was first selecting the dates and then adding them to the pivot. I have the desired table form, but not one line per persnr.
declare #dynQuery as nvarchar(MAX)
declare #cols as nvarchar(MAX)
select #cols= isnull(#cols + ',','')
+ quotename(convert(varchar, date, 104))
from (select distinct date from app_hours
where date between '01.01.2020' and '31.01.2020'
) AS Dates
SET #dynQuery =
N'select distinct persnr, ' + #cols + '
from app_hours
pivot (
sum(attendancetime)
for date in (' + #cols + '))
AS pivot where persnr = 000001'
EXEC sp_executesql #dynQuery
the table looks like this:
persnr 01.01.2020 02.01.2020 03.01.2020 [...]
----------------------------------------------------------------
000001 NULL NULL 5.00 ...
000001 NULL 5.00 NULL ...
000001 5.00 NULL NULL ...
Here is a way to add a floating subtotal placeholder to be offset from the last column of real data. This does not solve the column headers problem that was solved above, however, you could either create a SP to produce your headers laid out similarly or convert the pivot part to dynamic sql.
DECLARE #vReportData TABLE (
[persnr] int,
[date] datetime,
[abw] varchar(5),
[target] float,
[attendance] float
);
INSERT INTO #vReportData
([persnr], [date], [abw], [target], [attendance])
VALUES
(000001, '2020-01-01', '', 5.00, 4.45),
(000001, '2020-01-02', '', 0.00, 8.00),
(000001, '2020-01-04', '', 6.00, 7.00),
(000001, '2020-01-30', '', 6.00, 6.00),
(000001, '2020-01-31', '', 6.00, 6.50),
(999999, '2020-01-02', 'U', 6.00, 0.00),
(999999, '2020-01-30', '', 4.00, 5.00),
(999999, '2020-01-31', '', 5.00, 5.00)
declare #start datetime = '2020-01-01'
declare #ende datetime = '2020-01-04'
DECLARE #SubtotalPosition INT = DATEDIFF(DAY, #start,#ende) + 2
;with calender AS
(
select #start as Datum
union all
select Datum + 1 from Calender
where Datum + 1 <= #ende
)
,DistinctUsers AS
(
SELECT DISTINCT persnr FROM #vReportData
)
,MakeSubTotalPlaceholders AS
(
--Add placeholder to place at the end of the real data as subtotal buckets
select IsPlaceHolder=1, persnr, date = #ende, abw=null, target=0, attendance=null FROM DistinctUsers
UNION ALL
SELECT IsPlaceHolder=0, v.persnr, date, abw, target, attendance FROM #vReportData v
WHERE
v.date BETWEEN #start AND #ende
)
,ReadyForPivotWithTotal AS
(
SELECT
persnr, date, abw, target, attendance,
DayOffset = CASE WHEN IsPlaceHolder = 1 THEN #SubtotalPosition ELSE DENSE_RANK() OVER (ORDER BY DATEPART(DAY,date)) END,
total = CASE WHEN IsPlaceHolder = 1 THEN SUM(target) OVER (PARTITION BY persnr) ELSE target END
FROM
MakeSubTotalPlaceholders
)
SELECT persnr,
P1=MAX([1]),P2=MAX([2]),P3=MAX([3]),P4=MAX([4]),P5=MAX([5]),P6=MAX([6]),P7=MAX([7]),P8=MAX([8]),P9=MAX([9]),P10=MAX([10]),P11=MAX([11]),P12=MAX([12]),
P13=MAX([13]),P14=MAX([14]),P15=MAX([15]),P16=MAX([16]),P17=MAX([17]),P18=MAX([18]),P19=MAX([19]),P20=MAX([20]),P21=MAX([21]),P22=MAX([22]),P23=MAX([23]),P24=MAX([24]),
P25=MAX([25]),P26=MAX([26]),P27=MAX([27]),P28=MAX([28]),P29=MAX([29]),P30=MAX([30]),P31=MAX([31]),P32=MAX([32])
FROM
ReadyForPivotWithTotal A
PIVOT
(
MAX(total)
FOR DayOffSet IN
(
[1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],
[13],[14],[15],[16],[17],[18],[19],[20],[21],[22],[23],[24],
[25],[26],[27],[28],[29],[30],[31],[32]
)
)AS B
GROUP BY
persnr
Yes, the pain with pivots is having to name all the columns in your build statement, especially when that list is big or prone to change -- which, as you've pointed out, is best done with dynamic SQL.
I've used the EOMONTH function, a recursive CTE and a temp table to populate the list of pivot columns. Then used dynamic SQL to build and execute the PIVOT.
I need a little more clarity around what the [sum] column is actually adding, and your expected output for your example data set, before I can incorporate that.
But without the [sum] column...
-- declare vars
DECLARE #columns_select AS VARCHAR(MAX), #columns_pivot AS VARCHAR(MAX) ;
DECLARE #start_date AS DATE, #end_date AS DATE ;
DECLARE #sqlCmd AS NVARCHAR(MAX) ;
-- determine start date
SET #start_date = ( SELECT TOP(1) DATEADD ( DD, 1, EOMONTH ( [date], -1 ) )
FROM #vReportData ORDER BY [date] ASC ) ;
-- determine end date
SET #end_date = ( SELECT TOP(1) EOMONTH ( [date], 0 )
FROM #vReportData ORDER BY [date] DESC ) ;
-- generate date range to temp table
WITH cte_DateCols1 AS
(
SELECT #start_date AS [date]
UNION ALL
SELECT DATEADD ( DD, 1, [date] )
FROM cte_DateCols1
WHERE [date] < #end_date
)
SELECT [date]
INTO #tbl_Dates
FROM cte_DateCols1 ;
-- populate list of columns for SELECT statement
SELECT #columns_select = CONCAT ( #columns_select, ', ISNULL ( ', QUOTENAME ( [date] ), ', '''' ) AS '
, QUOTENAME ( CONVERT ( VARCHAR(10), [date], 104 ) ) )
FROM #tbl_Dates ;
-- populate list of columns for PIVOT statement
SELECT #columns_pivot = CONCAT ( #columns_pivot, ', ', QUOTENAME ( [date] ) )
FROM #tbl_Dates ;
SET #columns_pivot = RIGHT ( #columns_pivot, LEN ( #columns_pivot ) - 2 ) ;
-- drop temp table
DROP TABLE #tbl_Dates ;
-- build dynamic SQL PIVOT statement
SET #sqlCmd = N'
WITH cte_Data AS
(
SELECT [persnr]
, CAST ( [date] AS DATE ) AS [date]
, CASE [abw]
WHEN ''U'' THEN ''U''
WHEN '''' THEN CONCAT ( [attendance], ''/'', [target] )
ELSE NULL
END AS [result]
FROM #vReportData
)
SELECT RIGHT ( ''00000'' + CAST ( [persnr] AS VARCHAR(6) ), 6 ) AS [persnr]
' + #columns_select + '
FROM cte_Data
PIVOT (
MAX ( [result] )
FOR [date]
IN ( ' + #columns_pivot + ' )
) AS pvt
ORDER BY [persnr] ASC ;' ;
-- execute dynamic SQL PIVOT statement
PRINT #sqlCmd ;
EXEC sp_executesql #statement = #sqlCmd ;
GO
Updated for Attendance Totals
You should be able to grab the [attendance] totals using a SUM function on the CTE output, before applying the pivot, and tack it onto the end of your pivot output, like this...
-- declare vars
DECLARE #columns_select AS VARCHAR(MAX), #columns_pivot AS VARCHAR(MAX) ;
DECLARE #start_date AS DATE, #end_date AS DATE ;
DECLARE #sqlCmd AS NVARCHAR(MAX) ;
-- determine start date
SET #start_date = ( SELECT TOP(1) DATEADD ( DD, 1, EOMONTH ( [date], -1 ) )
FROM #vReportData ORDER BY [date] ASC ) ;
-- determine end date
SET #end_date = ( SELECT TOP(1) EOMONTH ( [date], 0 )
FROM #vReportData ORDER BY [date] DESC ) ;
-- generate date range to temp table
WITH cte_DateCols AS
(
SELECT #start_date AS [date]
UNION ALL
SELECT DATEADD ( DD, 1, [date] )
FROM cte_DateCols
WHERE [date] < #end_date
)
SELECT [date]
INTO #tbl_Dates
FROM cte_DateCols ;
-- populate list of columns for SELECT statement
SELECT #columns_select = CONCAT ( #columns_select, ', ISNULL ( ', QUOTENAME ( [date] ), ', '''' ) AS '
, QUOTENAME ( CONVERT ( VARCHAR(10), [date], 104 ) ) )
FROM #tbl_Dates ;
-- populate list of columns for PIVOT statement
SELECT #columns_pivot = CONCAT ( #columns_pivot, ', ', QUOTENAME ( [date] ) )
FROM #tbl_Dates ;
SET #columns_pivot = RIGHT ( #columns_pivot, LEN ( #columns_pivot ) - 2 ) ;
-- drop temp table
DROP TABLE #tbl_Dates ;
-- build dynamic SQL PIVOT statement
SET #sqlCmd = N'
WITH cte_Data AS
(
SELECT [persnr]
, CAST ( [date] AS DATE ) AS [date]
, CASE [abw]
WHEN ''U'' THEN ''U''
WHEN '''' THEN CONCAT ( [attendance], ''/'', [target] )
ELSE NULL
END AS [result]
FROM #vReportData
)
, cte_DataWithTotals AS
(
SELECT r.[persnr]
, SUM ( CAST ( r.[attendance] AS DECIMAL (5,2) ) ) AS [total_attendance]
, d.[date]
, d.[result]
FROM #vReportData AS r
INNER JOIN cte_Data AS d
ON r.[persnr] = d.[persnr]
GROUP BY r.[persnr], d.[date], d.[result]
)
SELECT RIGHT ( ''00000'' + CAST ( [persnr] AS VARCHAR(6) ), 6 ) AS [persnr]
' + #columns_select + '
, [total_attendance] AS [attendance_sum]
FROM cte_DataWithTotals
PIVOT (
MAX ( [result] )
FOR [date]
IN ( ' + #columns_pivot + ' )
) AS pvt
ORDER BY [persnr] ASC ;' ;
-- execute dynamic SQL PIVOT statement
PRINT #sqlCmd ;
EXEC sp_executesql #statement = #sqlCmd ;
GO

Column conflicts with the type of other columns unpivot list

I want execute this procedure, but SQL tell me this error 'The type of column "q82" conflicts with the type of other columns specified in the UNPIVOT list"
al the Q's are INT
Does somebody know solution?
INSERT INTO
[stg].[fact_answer_cc]
(
[user_id],
[question_id],
[answer],
[check_sum]
)
SELECT
[q2] AS [user_id],
[question_id],
[answer],
HASHBYTES (
N'SHA1',
ISNULL ( CAST([q2] AS VARCHAR), '' ) + #pipe_delimiter +
ISNULL ( CAST([question_id] AS VARCHAR), '' )
) AS [check_sum]
FROM
(
SELECT
[q2],
[q80],
[q81],
[q82],
[q83],
[q84],
[q85],
[q86],
[q87],
[q88],
[q89],
[q90],
[q91],
[q92]
FROM
[src].[qa_data_cc]
) AS t
UNPIVOT
(
[answer] FOR [question_id] IN
(
[q80],
[q81],
[q82],
[q83],
[q84],
[q85],
[q86],
[q87],
[q88],
[q89],
[q90],
[q91],
[q92]
)
) AS unpvt
ORDER BY
[user_id],
[question_id];
The type of column conflicts with the type of other columns specified in the UNPIVOT list.
Means your column' s data type same but it' s lenght differ.
Example:
q80 VARCHAR(10)
q82 VARCHAR(5)
Solution: #Cast all fields to fix value
CAST(q80 AS VARCHAR(10))
CAST(q82 AS VARCHAR(10))

SQL Server - Dynamic Pivot with 2 Group Variables and 2 Aggregate Calculations

I have a dataset that is shaped like this:
I am trying to convert the data to this format:
As you can see, I'd like to sum the accounts and revenue (for each month) by State and Account Type. It is important to note that I seek a dynamic solution as these ARE NOT the only values (hard-coding is not an option!).
What SQL query can I write to accomplish this task, dynamically? (as these values are not the only ones present in the complete dataset).
Thanks!
I'm assuming you want to keep the columns in order by date, thus the top 100 percent ... order by in the section where we generate the columns
Example
Declare #SQL varchar(max) = '
Select *
From (
Select [State]
,[AccountType]
,B.*
From YourTable A
Cross Apply ( values (concat(''Accounts_'',format([Date],''MM/dd/yyyy'')),Accounts)
,(concat(''Revenue_'' ,format([Date],''MM/dd/yyyy'')),Revenue)
) B (Item,Value)
) A
Pivot (sum([Value]) For [Item] in (' + Stuff((Select ','+QuoteName('Accounts_'+format([Date],'MM/dd/yyyy'))
+','+QuoteName('Revenue_' +format([Date],'MM/dd/yyyy'))
From (Select top 100 percent [Date] from YourTable Group By [Date] Order by [Date] ) A
For XML Path('')),1,1,'') + ') ) p'
--Print #SQL
Exec(#SQL)
Returns
If it helps, the generated SQL looks like this:
Select *
From (
Select [State]
,[AccountType]
,B.*
From YourTable A
Cross Apply ( values (concat('Accounts_',format([Date],'MM/dd/yyyy')),Accounts)
,(concat('Revenue_' ,format([Date],'MM/dd/yyyy')),Revenue)
) B (Item,Value)
) A
Pivot (sum([Value]) For [Item] in ([Accounts_12/31/2017],[Revenue_12/31/2017],[Accounts_01/31/2018],[Revenue_01/31/2018]) ) p

Missing Value Search in string seperated by comma

Please help me if it is possible in sql.
Hello, may anyone please share their expertise, i am not very sure whether it is possible in SQL
SIZE OF TABLE: 5GB
I am trying to see invalid VALIDATION_ID present in a child table for a given PRODUCT_LINE
SO in below scenario 114 is not present for PRODUCT_LINE Passive in master table but present in child table.
DECLARE #CHILD TABLE
(
PRODUCT_LINE VARCHAR (50),
COMPONENT VARCHAR (50),
MODEL VARCHAR (50),
YEARS VARCHAR (50),
VALIDATION_ID VARCHAR (50)
)
INSERT #CHILD
SELECT 'PASSIVE','RESISTOR','CARBON','2005','V114' UNION ALL
SELECT 'PASSIVE','RESISTOR','CARBON','2005','V098, E009, V034' UNION ALL
SELECT 'PASSIVE','RESISTOR','CARBON','2005','V201' UNION ALL
SELECT 'PASSIVE','RESISTOR','CARBON','2005','V201,V098,V114' UNION ALL
SELECT 'PASSIVE','RESISTOR','CARBON','2005',null UNION ALL
SELECT 'PASSIVE','RESISTOR','CARBON','2005','null,V098,E009' UNION ALL
SELECT 'PASSIVE','RESISTOR','CARBON','2005','null,V114' UNION ALL
SELECT * FROM #CHILD
DECLARE #PARENT TABLE
(
PRODUCT_LINE VARCHAR (50),
VALIDATION_ID VARCHAR (50)
)
INSERT #PARENT
SELECT 'PASSIVE','V098' UNION ALL
SELECT 'PASSIVE','E009' UNION ALL
SELECT 'PASSIVE','V201' UNION ALL
SELECT 'PASSIVE','V034'
EXPECTED OUTPUT
PRODUCT_LINE COMPONENT MODEL YEARS VALIDATION_ID INVALID_VALIDATION_ID
PASSIVE RESISTOR CARBON 2005 V114 V114
PASSIVE RESISTOR CARBON 2005 V201,V098,V114 V114
'PASSIVE','RESISTOR','CARBON','2005','null,V114',V114
Thanks ....
you will definately required a CSV splitter. There are many, just search for it. Here I am using Jeff's DelimitedSplit8K()
SELECT c.*, INVALID_VALIDATION_ID = v.Item
FROM #CHILD c
CROSS APPLY dbo.DelimitedSplit8K(c.VALIDATION_ID, ',') v
WHERE NOT EXISTS
(
SELECT *
FROM #PARENT p
WHERE p.PRODUCT_LINE = c.PRODUCT_LINE
and p.VALIDATION_ID = LTRIM(v.Item)
)
if there are more than one invalid ID, it will appear as multiple line. If you want the multiple invalid ID to appear as CSV, you will need additional query to concatenate it. Let me know if you required that
EDIT : Updated query to show invalid ID in CSV
; WITH
CTE AS
(
SELECT c.*, INVALID_VALIDATION_ID = v.Item,
RN = DENSE_RANK() OVER (ORDER BY PRODUCT_LINE, COMPONENT, MODEL, YEARS, VALIDATION_ID)
FROM #CHILD c
CROSS APPLY dbo.DelimitedSplit8K(c.VALIDATION_ID, ',') v
WHERE c.VALIDATION_ID IS NOT NULL -- edit [2]
AND NOT EXISTS
(
SELECT *
FROM #PARENT p
WHERE p.PRODUCT_LINE = c.PRODUCT_LINE
and p.VALIDATION_ID = LTRIM(v.Item)
)
)
SELECT DISTINCT
PRODUCT_LINE, COMPONENT, MODEL, YEARS, VALIDATION_ID,
INVALID_VALIDATION_ID = STUFF(csv, 1, 1, '')
FROM CTE c
CROSS APPLY
(
SELECT ',' + x.INVALID_VALIDATION_ID
FROM CTE x
WHERE x.RN = c.RN
ORDER BY INVALID_VALIDATION_ID
FOR XML PATH('')
) i (csv)
You Need to Try This...
SELECT *
FROM
(
SELECT c.*, INVALID_VALIDATION_ID = x.Value
FROM #CHILD c
CROSS APPLY dbo.Split(c.VALIDATION_ID, ',') x
WHERE NOT EXISTS
(
SELECT *
FROM #PARENT p
WHERE p.PRODUCT_LINE = c.PRODUCT_LINE
and p.VALIDATION_ID = x.Value
)
) AS Q
WHERE INVALID_VALIDATION_ID IS NOT NULL AND INVALID_VALIDATION_ID != 'null'
Here dbo.split function is ..
CREATE FUNCTION [dbo].[Split]
(#List varchar(8000),#SplitOn varchar(5))
RETURNS #RtnValue table
(Id int identity(1,1),Value nvarchar(100))
AS
BEGIN
Set #List = Replace(#List,'''','')
While (Charindex(#SplitOn,#List)>0)
Begin
Insert Into #RtnValue (value)
Select
Value = ltrim(rtrim(Substring(#List,1,Charindex(#SplitOn,#List)-1)))
Set #List = Substring(#List,Charindex(#SplitOn,#List)+len(#SplitOn),len(#List))
End
Insert Into #RtnValue (Value)
Select Value = ltrim(rtrim(#List))
Return
END
try this......