:
:
insert into Lists(name, listid, storeid, customerid) values('AnotherNew',3,11,100);
insert into Lists(name, listid, storeid, customerid) values('AnotherNew',3,11,102);
insert into Lists(name, listid, storeid, customerid) values('AnotherNew',3,10,100);
:
EDIT: - - , customerid storeid
DECLARE @listNames VARCHAR(MAX)=
STUFF(
(
SELECT DISTINCT ',[' + name + ']'
FROM Lists
FOR XML PATH('')
),1,1,'');
DECLARE @SqlCmd VARCHAR(MAX)=
'
WITH DistinctCombinations AS
(
SELECT DISTINCT customerid,storeid
FROM Lists AS l
)
SELECT p.*
FROM
(
SELECT DistinctCombinations.*
,OtherExisting.name AS OtherName
,CASE WHEN l.listid IS NULL THEN '''' ELSE ''X'' END AS ExistingValue
FROM DistinctCombinations
LEFT JOIN Lists AS l ON DistinctCombinations.customerid=l.customerid AND DistinctCombinations.storeid=l.storeid
OUTER APPLY
(
SELECT x.name
FROM Lists AS x
WHERE x.customerid=l.customerid
AND x.storeid=l.storeid
) AS OtherExisting
) AS tbl
PIVOT
(
MIN(ExistingValue) FOR OtherName IN (' + @ListNames + ')
) AS p';
EXEC(@SqlCmd);
customerid storeid AnotherNew BaseList NewList
100 10 X X NULL
100 11 X X X
102 11 X X NULL
102 12 NULL NULL X
103 12 NULL NULL X
:
DECLARE @listNames VARCHAR(MAX)=
STUFF(
(
SELECT DISTINCT ',[' + name + ']'
FROM Lists
FOR XML PATH('')
),1,1,'');
DECLARE @SqlCmd VARCHAR(MAX)=
'
WITH DistinctLists AS
(
SELECT DISTINCT listid
FROM Lists AS l
)
SELECT p.*
FROM
(
SELECT l.*
,OtherExisting.name AS OtherName
,CASE WHEN l.listid IS NULL THEN '''' ELSE ''X'' END AS ExistingValue
FROM DistinctLists
INNER JOIN Lists AS l ON DistinctLists.listid= l.listid
CROSS APPLY
(
SELECT x.name
FROM Lists AS x
WHERE x.listid<>l.listid
AND x.customerid=l.customerid
AND x.storeid=l.storeid
) AS OtherExisting
) AS tbl
PIVOT
(
MIN(ExistingValue) FOR OtherName IN (' + @ListNames + ')
) AS p';
EXEC(@SqlCmd);
:
name listid storeid customerid AnotherNew BaseList NewList
AnotherNew 3 10 100 NULL X NULL
AnotherNew 3 11 100 NULL X X
AnotherNew 3 11 102 NULL X NULL
BaseList 1 10 100 X NULL NULL
BaseList 1 11 100 X NULL X
BaseList 1 11 102 X NULL NULL
NewList 2 11 100 X X NULL