This uses string concatenations to determine which ids share LineGroupBy values. It also ensures the ids aren't repeated and are ordered.
SELECT Groups.LineGroupBy, STUFF((
SELECT ',' + CAST(t2.id AS VARCHAR(20))
FROM (select distinct LineGroupBy, Id from temp) t2
WHERE Groups.LineGroupBy = t2.LineGroupBy
ORDER BY t2.id
FOR XML PATH('')
), 1, 1, '') AS IdList
FROM (SELECT DISTINCT LineGroupBy FROM temp) AS Groups
LineGroupBy |
IdList |
BankAccountId |
1,5,6,8 << test data: this is common to all ids |
CurrencyId |
5,6 |
FundTypeId |
5,6 |
InOut |
5,6 |
ItemId |
1,6,8 |
ItemTypeId |
1,6,8 |
VATId |
1,6 |
VATPer |
1,6 |
Then we add a comparison of that result (above) to the distinct list of ids, so that the where clause is also automated:
WITH CTE as (
SELECT Groups.LineGroupBy, STUFF(
(
SELECT ',' + CAST(t2.id AS VARCHAR(20))
FROM (SELECT DISTINCT LineGroupBy, Id FROM temp) t2
WHERE Groups.LineGroupBy = t2.LineGroupBy
ORDER BY t2.id
FOR XML PATH('')
), 1, 1, '') AS IdList
FROM (SELECT DISTINCT LineGroupBy FROM temp) AS Groups
)
SELECT LineGroupBy, IdList
FROM CTE
WHERE IdList = (
SELECT STUFF((
SELECT ',' + CAST(id AS VARCHAR(20))
FROM (SELECT DISTINCT Id FROM temp) t
ORDER BY id
FOR XML PATH('')
), 1, 1, '')
)
LineGroupBy |
IdList |
BankAccountId |
1,5,6,8 |
fiddle
Original post:
I'm unsure what you are really asking for as you have not specified any actual output, but thought perhaps this may help:
SELECT Groups.LineGroupBy, STUFF((
SELECT ',' + CAST(t2.id AS VARCHAR(20))
FROM temp t2
WHERE Groups.LineGroupBy = t2.LineGroupBy
FOR XML PATH('')
), 1, 1, '') AS IdList
FROM (SELECT DISTINCT LineGroupBy FROM temp) AS Groups
From the given sample data:
LineGroupBy |
IdList |
BankAccountId |
5 |
CurrencyId |
5 |
FundTypeId |
5 |
InOut |
5 |
ItemId |
1,8 |
ItemTypeId |
8,1 |
VATId |
1 |
VATPer |
1 |
INSERT INTO temp (LineGroupBy, Id)
VALUES
('ItemTypeId',6),
('ItemId',6),
('BankAccountId',6),
('ItemTypeId',6),
('VATId',6),
('InOut',6),
('FundTypeId',6),
('CurrencyId',6),
('VATPer',6)
;
after adding some extra data
LineGroupBy |
IdList |
BankAccountId |
5,6 |
CurrencyId |
5,6 |
FundTypeId |
5,6 |
InOut |
5,6 |
ItemId |
1,8,6 |
ItemTypeId |
8,1,6,6 |
VATId |
1,6 |
VATPer |
1,6 |
fiddle