I have four tables - tblBase, tblLookup, tblData and tblData2
tblBase
+---------+----------+-----------+------------+
| Base_ID | Base_Num | Base_Type | Base_Date |
+---------+----------+-----------+------------+
| 1 | 1234 | ABC | 01/05/2016 |
| 2 | 3456 | DEF | 02/05/2016 |
| 3 | 7890 | GHI | 03/05/2016 |
+---------+----------+-----------+------------+
tblLookup
+-----------+-------------+
| Lookup_ID | Lookup_Name |
+-----------+-------------+
| 1 | Apple |
| 2 | Orange |
| 3 | Banana |
+-----------+-------------+
tblData
+-----------+----------+------------+
| Data_Name | Data_Num | Data_Date |
+-----------+----------+------------+
| Apple | 1234 | 02/05/2016 |
| Orange | 3456 | 03/05/2016 |
| Guava | 5937 | 04/05/2016 |
+-----------+----------+------------+
tblData2
+------------+-----------+------------+
| Data2_Name | Data2_Num | Data2_Date |
+------------+-----------+------------+
| Grapes | 3953 | 02/05/2016 |
| Orange | 3456 | 03/05/2016 |
| Banana | 7890 | 04/05/2016 |
| Banana | 1473 | 07/05/2016 |
+------------+-----------+------------+
I am trying to get the Data_Date from tblData or tblData2 (where ever the data exists) join with tblBase where Base_Num matches . As the common columns exists in tblLookup, I need to join all the four tables.
For example, Base_ID = 3, Base_Num = 7890, should pick up Data_Date from tblData2, as both Base_ID (Banana) and Base_Num (7890) matches.
I tried doing INNER JOIN however it did not give the desired result.
I'm looking for a resulting table like this:
+---------+----------+-----------+------------+-------------------+
| Base_ID | Base_Num | Base_Type | Base_Date | Desired_Data_Date |
+---------+----------+-----------+------------+-------------------+
| 1 | 1234 | ABC | 01/05/2016 | 02/05/2016 |
| 2 | 3456 | DEF | 02/05/2016 | 03/05/2016 |
| 3 | 7890 | GHI | 03/05/2016 | 04/05/2016 |
+---------+----------+-----------+------------+-------------------+
You may try Left Join
SELECT B.Base_ID, B.Base_Num , B.Base_Type, B.Base_Date,
D1.Data_Name AS Data1, D1.Data_Date AS DESIRED_DATE1
D2.Data2_Name AS Data2, D2.Data2_Date AS DESIRED_
FROM tblBase B
JOIN tblLookup L ON L.Lookup_ID=B.Base_ID
LEFT JOIN tblData D1 ON D1.Data_Num = B.Base_Num
LEFT JOIN tblData2 D2 ON D2.Data2_Num = B.Base_Num
WHERE <Condition>
declare #tblbase table (Base_ID int, Base_Num int, Base_Type varchar(3), Base_Date varchar(10))
Insert into #tblbase
values
( 1 , 1234 , 'ABC', '01/05/2016'),
( 2 , 3456 , 'DEF', '02/05/2016'),
( 3 , 7890 , 'GHI', '03/05/2016')
declare #tblLookup table (Lookup_ID int, Lookup_Name varchar(10))
insert into #tblLookup
values
( 1 , 'Apple' ),
( 2 , 'Orange'),
( 3 , 'Banana')
declare #tbldata table (Data_Name varchar(10), Data_Num int, Data_Date varchar(10))
Insert into #tbldata
values
( 'Apple' , 1234 , '02/05/2016'),
( 'Orange' , 3456 , '03/05/2016'),
( 'Guava' , 5937 , '04/05/2016')
declare #tbldata2 table (Data_Name varchar(10), Data_Num int, Data_Date varchar(10))
Insert into #tbldata2
values
( 'Grapes', 3953 , '02/05/2016'),
( 'Orange' , 3456 , '03/05/2016'),
( 'Banana' , 7890 , '04/05/2016'),
( 'Banana' , 1473 , '07/05/2016')
/*
Expected result
+---------+----------+-----------+------------+-------------------+
| Base_ID | Base_Num | Base_Type | Base_Date | Desired_Data_Date |
+---------+----------+-----------+------------+-------------------+
| 1 | 1234 | ABC | 01/05/2016 | 02/05/2016 |
| 2 | 3456 | DEF | 02/05/2016 | 03/05/2016 |
| 3 | 7890 | GHI | 03/05/2016 | 04/05/2016 |
+---------+----------+-----------+------------+-------------------+
*/
select bt.*,u.data_date as Desired_data_date
from #tblbase bt
join #tblLookup lu on lu.lookup_id = bt.base_id
join
(select t1.* from #tbldata t1
union
select t2.* from #tbldata2 t2
) u
on u.data_name = lu.Lookup_Name
where u.Data_Num = bt.Base_Num
order by bt.Base_Date
Related
I want to join 2 tables such that I get the NAR for every combination of Type and BillingID where it exists.
Where a BillingID doesn't have a certain Type, then either NULL or 0 is returned for the NAR along with the Type and BillingID.
Is something like this even possible using SQL?
A simplified version of my data is shown below:
Type list:
+----------+
| Type |
+----------+
| NEW |
| CHNG |
| LAP |
+----------+
Data:
+----------+-----------+-----+
| Type | BillingID | NAR |
+----------+-----------+-----+
| NEW | ABC | 5 |
| CHNG | ABC | 15 |
| LAP | ABC | 10 |
| CHNG | DEF | 20 |
+----------+-----------+-----+
Desired result:
+----------+-----------+-----+
| Type | BillingID | NAR |
+----------+-----------+-----+
| NEW | ABC | 5 |
| CHNG | ABC | 15 |
| LAP | ABC | 10 |
| CHNG | DEF | 20 |
| NEW | DEF | 0 |
| LAP | DEF | 0 |
+----------+-----------+-----+
The last 2 rows are what is causing me problems.
I think you can do it like this:
declare #table table (type1 varchar(5))
insert into #table
values
('new'),
('chng'),
('lap')
declare #table2 table (typeid varchar(5),billingid varchar(5),nar int)
insert into #table2
values
( 'NEW', 'ABC', 5 ),
( 'CHNG' , 'ABC', 15 ),
( 'LAP' , 'ABC', 10 ),
( 'CHNG' , 'DEF', 20 )
select Z.*,case when c.nar IS null then 0 else c.nar end as nar from (
select * from #table a
outer apply (select distinct billingid from #table2 b ) p
)Z
left join #table2 c on Z.type1 = c.typeid and Z.billingid = c.billingid
order by billingid
Result
I am using an SQL Server database and have these following tables
Table "Data"
------------------
| Id | data_name |
------------------
| 1 |Data 1 |
| 2 |Data 2 |
| 3 |Data 3 |
| 4 |Data 4 |
| 5 |Data 5 |
------------------
and Table "Value_data"
--------------------------------------------------------------------------------------------------------------
| Id | data_id | date | col_1_type | col_1_name | col_1_value | col_2_type | col_2_name | col_2_value |
--------------------------------------------------------------------------------------------------------------
| 1 | 1 | 2017-01-01 | A | Alpha | 12 | B | Beta | 23 |
| 2 | 1 | 2017-02-01 | A | Alpha | 32 | B | Beta | 42 |
---------------------------------------------------------------------------------------------------------------
And i want to make result like so
-----------------------------------------------------------------
|value_id | data_id | data_name | date | A-Alpha | B-Beta |
-----------------------------------------------------------------
|1 | 1 | Data 1 | 2017-01-01 | 12 | 23 |
|2 | 1 | Data 1 | 2017-02-01 | 32 | 42 |
-----------------------------------------------------------------
I've search multiple times for solutions, i've tried using Pivot for example for a static result,
DECLARE #Data TABLE ( Id INT, data_name VARCHAR(10) )
INSERT INTO #Data VALUES
( 1 ,'Data 1'),
( 2 ,'Data 2'),
( 3 ,'Data 3'),
( 4 ,'Data 4'),
( 5 ,'Data 5')
DECLARE #Value_data TABLE (Id INT, data_id INT, [date] DATE, col_1_type VARCHAR(10), col_1_name VARCHAR(10), col_1_value INT, col_2_type VARCHAR(10), col_2_name VARCHAR(10), col_2_value INT)
INSERT INTO #Value_data VALUES
( 1, 1, '2017-01-01','A','Alpha','12','B','Beta','23'),
( 2, 1, '2017-02-01','A','Alpha','32','B','Beta','42')
;WITH CTE AS (
select vd.Id value_id
, vd.data_id
, d.data_name
, vd.[date]
, vd.col_1_type + '-' +vd.col_1_name Col1
, vd.col_1_value
, vd.col_2_type + '-' +vd.col_2_name Col2
, vd.col_2_value
from #Value_data vd
inner join #Data d on vd.data_id = d.Id
)
SELECT * FROM CTE
PIVOT( MAX(col_1_value) FOR Col1 IN ([A-Alpha])) PVT_A
PIVOT( MAX(col_2_value) FOR Col2 IN ([B-Beta])) PVT_B
but it wont work well with the data that i'm using with the joining tables because my database will be dynamic, anyone had a solution with the same case?
I'm having a serious problem with one of my import tables. I've imported an Excel file to a SQL Server table. The table ImportExcelFile now looks like this (simplified):
+----------+-------------------+-----------+------------+--------+--------+-----+---------+
| ImportId | Excelfile | SheetName | Field1 | Field2 | Field3 | ... | Field10 |
+----------+-------------------+-----------+------------+--------+--------+-----+---------+
| 1 | C:\Temp\Test.xlsx | Sheet1 | Age / Year | 2010 | 2011 | | 2018 |
| 2 | C:\Temp\Test.xlsx | Sheet1 | 0 | Value1 | Value2 | | Value9 |
| 3 | C:\Temp\Test.xlsx | Sheet1 | 1 | Value1 | Value2 | | Value9 |
| 4 | C:\Temp\Test.xlsx | Sheet1 | 2 | Value1 | Value2 | | Value9 |
| 5 | C:\Temp\Test.xlsx | Sheet1 | 3 | Value1 | Value2 | | Value9 |
| 6 | C:\Temp\Test.xlsx | Sheet1 | 4 | Value1 | Value2 | | Value9 |
| 7 | C:\Temp\Test.xlsx | Sheet1 | 5 | NULL | NULL | | NULL |
+----------+-------------------+-----------+------------+--------+--------+-----+---------+
I now want to insert those values from Field1 to Field10 to the table AgeYear(in my original table there are about 70 columns and 120 rows). The first row (Age / Year, 2010, 2011, ...) is the header row. The column Field1 is the leading column. I want to save the values in the following format:
+-----------+-----+------+--------+
| SheetName | Age | Year | Value |
+-----------+-----+------+--------+
| Sheet1 | 0 | 2010 | Value1 |
| Sheet1 | 0 | 2011 | Value2 |
| ... | ... | ... | ... |
| Sheet1 | 0 | 2018 | Value9 |
| Sheet1 | 1 | 2010 | Value1 |
| Sheet1 | 1 | 2011 | Value2 |
| ... | ... | ... | ... |
| Sheet1 | 1 | 2018 | Value9 |
| ... | ... | ... | ... |
+-----------+-----+------+--------+
I've tried the following query:
DECLARE #sql NVARCHAR(MAX) =
';WITH cte AS
(
SELECT i.SheetName,
ROW_NUMBER() OVER(PARTITION BY i.SheetName ORDER BY i.SheetName) AS rn,
' + #columns + ' -- #columns = 'Field1, Field2, Field3, Field4, ...'
FROM dbo.ImportExcelFile i
WHERE i.Sheetname LIKE ''Sheet1''
)
SELECT SheetName,
age Age,
y.[Year]
FROM cte
CROSS APPLY
(
SELECT Field1 age
FROM dbo.ImportExcelFile
WHERE SheetName LIKE ''Sheet1''
AND ISNUMERIC(Field1) = 1
) a (age)
UNPIVOT
(
[Year] FOR [Years] IN (' + #columns + ')
) y
WHERE rn = 1'
EXEC (#sql)
So far I'm getting the desired ages and years. My problem is that I don't know how I could get the values. With UNPIVOT I don't get the NULL values. Instead it fills the whole table with the same values even if they are NULL in the source table.
Could you please help me?
Perhaps an alternative approach. This is not dynamic, but with the help of a CROSS APPLY and a JOIN...
The drawback is that you'll have to define the 70 fields.
Example
;with cte0 as (
Select A.ImportId
,A.SheetName
,Age = A.Field1
,B.*
From ImportExcelFile A
Cross Apply ( values ('Field2',Field2)
,('Field3',Field3)
,('Field10',Field10)
) B (Item,Value)
)
,cte1 as ( Select * from cte0 where ImportId=1 )
Select A.SheetName
,[Age] = try_convert(int,A.Age)
,[Year] = try_convert(int,B.Value)
,[Value] = A.Value
From cte0 A
Join cte1 B on A.Item=B.Item
Where A.ImportId>1
Returns
I have not found an answer yet, so this may not be possible.
I am looking for a pivot query that will replace a pivoted NULL row with the last value available for the column that was not NULL. If the First row is Null then rows are NULL until a row has a value.
Updated When CID changes the rows start as new rows. So if the first row of CID 3 is Null, then the value is null.
Here is my pivot query
DECLARE #Columns AS VARCHAR(MAX)
DECLARE #Query VARCHAR(MAX)
DECLARE #TEMP_DB VARCHAR(255)
SET #TEMP_DB = 'Demo_DataSet'
SELECT #Columns =
COALESCE(#Columns + ', ','') + QUOTENAME(AttrName)
FROM
(
SELECT DISTINCT AttrName
FROM Demo_FirstPass_Data_Raw
) AS B
ORDER BY B.AttrName
SET #Query = '
WITH PivotData AS
(
SELECT
DocID
, Customer
, Version
, CID
, AttrName
, AttrText
FROM Demo_FirstPass_Data_Raw
)
SELECT
DocID
, Customer
, Version
, CID
, ' + #Columns + '
INTO Demo_FirstPass_Data_Pivot
FROM PivotData
PIVOT
(
MAX(AttrText)
FOR AttrName
IN (' + #Columns + ')
) AS PivotResult
Where Version = Version
ORDER BY DocID, Version, CID'
DECLARE #SQL_SCRIPT VARCHAR(MAX)
SET #SQL_SCRIPT = REPLACE(#Query, '' + #TEMP_DB + '', #TEMP_DB)
EXECUTE (#SQL_SCRIPT)
My result is
DocID | Customer | Version | CID | Username | Sales_Order | Date | Description
1852 | Acme | 1 | 2 | User1 | NULL | 11/17/2010 | Product
1852 | Acme | 2 | 2 | NULL | NULL | NULL | NULL
1852 | Acme | 3 | 2 | NULL | NULL | 12/15/2010 | NULL
1852 | Acme | 4 | 2 | NULL | NULL | NULL | NULL
1852 | Acme | 5 | 2 | NULL | S-0001 | 11/17/2010 | NULL
1852 | Acme | 7 | 2 | NULL | S-0001 | NULL | NULL
1852 | Acme | 8 | 2 | NULL | NULL | 1/14/2011 | NULL
1852 | Acme | 9 | 2 | NULL | NULL | NULL | NULL
1852 | Acme | 10 | 2 | NULL | NULL | NULL | NULL
1852 | Acme | 1 | 3 | User2 | NULL | 10/10/2010 | Product
1852 | Acme | 2 | 3 | NULL | NULL | NULL | NULL
1852 | Acme | 3 | 3 | NULL | NULL | 12/15/2010 | NULL
What I am looking for is
DocID | Customer | Version | CID | Username | Sales_Order | Date | Description
1852 | Acme | 1 | 2 | User1 | NULL | 11/17/2010 | Product
1852 | Acme | 2 | 2 | User1 | NULL | 11/17/2010 | Product
1852 | Acme | 3 | 2 | User1 | NULL | 12/15/2010 | Product
1852 | Acme | 4 | 2 | User1 | NULL | 12/15/2010 | Product
1852 | Acme | 5 | 2 | User1 | S-0001 | 11/17/2010 | Product
1852 | Acme | 7 | 2 | User1 | S-0001 | 11/17/2010 | Product
1852 | Acme | 8 | 2 | User1 | S-0001 | 1/14/2011 | Product
1852 | Acme | 9 | 2 | User1 | S-0001 | 1/14/2011 | Product
1852 | Acme | 10 | 2 | User1 | S-0001 | 1/14/2011 | Product
1852 | Acme | 1 | 3 | User2 | NULL | 10/10/2010 | Product
1852 | Acme | 2 | 3 | User2 | NULL | 10/10/2010 | Product
1852 | Acme | 3 | 3 | User2 | NULL | 12/15/2010 | Product
Any help is appreciated.
For an unknown number of columns and to integrate into a dynamic pivot, one option is to generate the code for a recursive cte and use that to retain the last non null value based on your partitions like so:
declare #Columns as nvarchar(max)
declare #Query nvarchar(max)
declare #temp_db nvarchar(255)
set #temp_db = 'Demo_DataSet'
select #Columns =
coalesce(#Columns + ', ','') + quotename(AttrName)
from
(
select distinct AttrName
from Demo_FirstPass_Data_Raw
) as B
order by B.AttrName
/* generate isnull statements for columns in recursive cte */
declare #isnull nvarchar(max) = stuff((
select distinct ', isnull(t.'+quotename(d.AttrName)+',cte.'+quotename(d.AttrName)+')'
from Demo_FirstPass_Data_Raw d
order by 1
for xml path (''), type).value('(./text())[1]','nvarchar(max)')
,1,2,'')
set #Query = 'with PivotData as (
select Docid, Customer, Version, cid, AttrName, AttrText
from Demo_FirstPass_Data_Raw
)
, t as (
select
Docid, Customer, Version, cid
, ' + #Columns + '
, rn = row_number() over (partition by DocId, Customer, cid order by Version)
from PivotData
pivot(max(AttrText) for AttrName in (' + #Columns + ')) as PivotResult
)
, cte as (
select [Docid], [Customer], [Version], [cid], ' + #Columns + ', rn
from t
where version = 1
union all
select t.[Docid], t.[Customer], t.[Version], t.[cid]
, '+ #isnull + '
'+',t.rn
from t
inner join cte
on t.rn = cte.rn+1
and t.docid = cte.docid
and t.customer = cte.customer
and t.cid = cte.cid
)
select *
from cte
order by docid, customer, cid, version
'
select #query
exec sp_executesql #query
rextester demo: http://rextester.com/OQZOW62536
code generated:
with PivotData as (
select Docid, Customer, Version, cid, AttrName, AttrText
from Demo_FirstPass_Data_Raw
)
, t as (
select
Docid, Customer, Version, cid
, [Date], [Description], [Sales_Order], [Username]
, rn = row_number() over (partition by DocId, Customer, cid order by Version)
from PivotData
pivot(max(AttrText) for AttrName in ([Date], [Description], [Sales_Order], [Username])) as PivotResult
)
, cte as (
select [Docid], [Customer], [Version], [cid], [Date], [Description], [Sales_Order], [Username], rn
from t
where version = 1
union all
select t.[Docid], t.[Customer], t.[Version], t.[cid]
, isnull(t.[Date],cte.[Date]), isnull(t.[Description],cte.[Description]), isnull(t.[Sales_Order],cte.[Sales_Order]), isnull(t.[Username],cte.[Username])
,t.rn
from t
inner join cte
on t.rn = cte.rn+1
and t.docid = cte.docid
and t.customer = cte.customer
and t.cid = cte.cid
)
select *
from cte
order by docid, customer, cid, version
results:
+-------+----------+---------+-----+------------+-------------+-------------+----------+----+
| Docid | Customer | Version | cid | Date | Description | Sales_Order | Username | rn |
+-------+----------+---------+-----+------------+-------------+-------------+----------+----+
| 1852 | Acme | 1 | 2 | 2010-11-17 | Product | NULL | User1 | 1 |
| 1852 | Acme | 2 | 2 | 2010-11-17 | Product | NULL | User1 | 2 |
| 1852 | Acme | 3 | 2 | 2010-12-15 | Product | NULL | User1 | 3 |
| 1852 | Acme | 4 | 2 | 2010-12-15 | Product | NULL | User1 | 4 |
| 1852 | Acme | 5 | 2 | 2010-11-17 | Product | S-0001 | User1 | 5 |
| 1852 | Acme | 7 | 2 | 2010-11-17 | Product | S-0001 | User1 | 6 |
| 1852 | Acme | 8 | 2 | 2011-01-14 | Product | S-0001 | User1 | 7 |
| 1852 | Acme | 9 | 2 | 2011-01-14 | Product | S-0001 | User1 | 8 |
| 1852 | Acme | 10 | 2 | 2011-01-14 | Product | S-0001 | User1 | 9 |
| 1852 | Acme | 1 | 3 | 2010-10-10 | Product | NULL | User2 | 1 |
| 1852 | Acme | 2 | 3 | 2010-10-10 | Product | NULL | User2 | 2 |
| 1852 | Acme | 3 | 3 | 2010-12-15 | Product | NULL | User2 | 3 |
+-------+----------+---------+-----+------------+-------------+-------------+----------+----+
I am using SQL Server 2012.
I have this table called InspectionReviews:
|Id | SiteId| IsNormal| DateReview | ObjectId |FrequencyId|InspectItemId |
|3379| 5| True | 2016-09-08 00:00:00.000| 1019 | 1 | 16 |
|3380| 5| True | 2016-09-08 00:00:00.000| 1019 | 1 | 20 |
|3381| 5| False | 2016-09-08 00:00:00.000| 1020 | 1 | 16 |
|3382| 5| True | 2016-09-08 00:00:00.000| 1020 | 1 | 54 |
IsNormal is a bit column.
And this table called DamageEvents:
| Id | ExternalId | Subject | CMT |
| 1 | 3379 | damage5 | some comment7 |
| 2 | 3380 | damage3 | some comment3 |
| 3 | 3382 | damage4 | some comment5 |
| 4 | 3381 | damage1 | some comment4 |
The ExternalId column in DamageEvents table is a foreign key.
I wrote an inner join between the two tables:
SELECT
InspectionReviews.Id, InspectionReviews.SiteId,
InspectionReviews.IsNormal, InspectionReviews.DateReview,
InspectionReviews.ObjectId, InspectionReviews.FrequencyId,
InspectionReviews.InspectItemId,
DamageEvents.ExternalId, DamageEvents.Subject, DamageEvents.CMT,
FROM
InspectionReviews
INNER JOIN
DamageEvents ON InspectionReviews.Id = DamageEvents.ExternalId
The result I get:
|Id | SiteId| IsNormal| DateReview | ObjectId |FrequencyId|InspectItemId | ExternalId | Subject | CMT |
|3379| 5 | True | 2016-09-08 00:00:00.000| 1019 | 1 | 16 | 3379 | damage5 | some comment7 |
|3380| 5 | True | 2016-09-08 00:00:00.000| 1019 | 1 | 20 | 3380 | damage3 | some comment3 |
|3381| 5 | False | 2016-09-08 00:00:00.000| 1020 | 1 | 16 | 3381 | damage4 | some comment5 |
|3382| 5 | True | 2016-09-08 00:00:00.000| 1020 | 1 | 54 | 3382 | damage1 | some comment4 |
After I implement inner join I need to make group by ObjectId. And here is desired result:
| Id | SiteId| IsNormal| DateReview | ObjectId |FrequencyId|InspectItemId | Subject | CMT |
|3379,3380| 5 | True | 2016-09-08 00:00:00.000| 1019 | 1 | 16,20 | damage5 | some comment7,some comment3 |
|3381,3382| 5 | False | 2016-09-08 00:00:00.000| 1020 | 1 | 16,54 | damage4 | some comment5,some comment4 |
I need to group the table above after (inner join) by ObjectId, if at least one row has IsNormal false in grouped table it have to be False.
How can I implement it?
You can use query like this:
; with cte as (
SELECT InspectionReviews.Id,
InspectionReviews.SiteId,
InspectionReviews.IsNormal,
InspectionReviews.DateReview,
InspectionReviews.ObjectId,
InspectionReviews.FrequencyId,
InspectionReviews.InpectItemId,
DamageEvents.ExternalId,
DamageEvents.Subject,
DamageEvents.CMT
FROM #inspectionreviews InspectionReviews INNER JOIN
#damageevents DamageEvents ON InspectionReviews.Id = DamageEvents.ExternalId
)
select objectid, min(convert(int,IsNormal)) as IsNormal , stuff ((
select ',' + convert(varchar(5),Id) from cte where objectid = t.objectid
for xml path('')
),1,1,'') as Id
, stuff ((
select ',' + convert(varchar(5),inpectitemid) from cte where objectid = t.objectid
for xml path('')
),1,1,'') as InspectItemId
, stuff ((
select ',' + subject from cte where objectid = t.objectid
for xml path('')
),1,1,'') as Subject
, stuff ((
select ',' + CMT from cte where objectid = t.objectid
for xml path('')
),1,1,'') as CMT,
max(frequencyid) as FrequencyId,
max(SiteId) as SiteId
from cte t group by objectid
May this help-
select
ObjectId,
Id = Stuff( (select ',' + convert(varchar(100), Id)
from InspectionReviews
where ObjectId = ir.ObjectId for xml path('')), 1, 1, ''),
IsNormal = Min(convert(int, IsNormal))
from
InspectionReviews ir
group by
ObjectId