I've seen similar questions posted here but either I don't get the answers or they don't apply... here is what I need and thought it would be really simple: I have a set of items and each item has a set of subitems. The number of subitems changes per item. E.G.:
Item 1
SubItem 1-1
SubItem 1-2
SubItem 1-3
Item 2
SubItem 2-1
Item 3
SubItem 3-1
SubItem 3-2
For a very specific use, the want is to add a comment for every possible combination of subitems on each item, plus a boolean property on each subitem, so it ends up like this:
Item 1 Subitem 1-1 = True, Subitem 1-2 = True, Subitem 1-3 = True
Item 1 Subitem 1-1 = True, Subitem 1-2 = True, Subitem 1-3 = False
Item 1 Subitem 1-1 = True, Subitem 1-2 = False, Subitem 1-3 = True
Item 1 Subitem 1-1 = True, Subitem 1-2 = False, Subitem 1-3 = False
Item 1 Subitem 1-1 = False, Subitem 1-2 = True, Subitem 1-3 = True
... (the rest of Item 1 possible combinations)
Item 2 Subitem 2-1 = True
Item 2 Subitem 2-1 = False
Item 3 Subitem 3-1 = True, Subitem 3-2 = True
Item 3 Subitem 3-1 = True, Subitem 3-2 = False
Item 3 Subitem 3-1 = False, Subitem 3-2 = True
Item 3 Subitem 3-1 = False, Subitem 3-2 = False
I've tried a varietè of inner joins and cross joins but could not make it work. I think the boolean part can be added using a cross join to a table with two rows that have the values True and False, and I also think I need to do a "FOR XML" subquery to get the subitems in a single line, but I'm failing to get the subitems combinations
This is what I have so far:
-- Schema creation and data filling
DECLARE @Item TABLE (ItemId int, Name varchar(50))
DECLARE @Item_SubItem TABLE (ItemId int, SubitemId int)
DECLARE @SubItem TABLE (SubitemId int, Name varchar(50))
INSERT INTO @Item values (1, 'Item 1')
INSERT INTO @Item values (2, 'Item 2')
INSERT INTO @Item values (3, 'Item 3')
INSERT INTO @SubItem values (1, 'SubItem 1-1')
INSERT INTO @SubItem values (2, 'SubItem 1-2')
INSERT INTO @SubItem values (3, 'SubItem 1-3')
INSERT INTO @SubItem values (4, 'SubItem 2-1')
INSERT INTO @SubItem values (5, 'SubItem 3-1')
INSERT INTO @SubItem values (6, 'SubItem 3-2')
INSERT INTO @Item_SubItem values (1, 1)
INSERT INTO @Item_SubItem values (1, 2)
INSERT INTO @Item_SubItem values (1, 3)
INSERT INTO @Item_SubItem values (2, 4)
INSERT INTO @Item_SubItem values (3, 5)
INSERT INTO @Item_SubItem values (3, 6)
select I.Name, SI.Name
from @Item I
inner join @Item_SubItem ISI on ISI.ItemId = I.ItemId
INNER JOIN @SubItem SI on SI.SubitemId = ISI.SubitemId
order by I.Name, SI.Name
-- Actual query
SELECT ItemName = M.name, (SELECT iC.name + '=' + CASE AuxCode WHEN 1 THEN 'True' WHEN 0 THEN 'False' END + ' '
FROM Item_subitem AS iCGM
INNER JOIN Subitem AS iC ON iC.SubitemId = iCGM.SubitemId
CROSS JOIN (SELECT AuxCode = 1 UNION SELECT AuxCode = 0) Aux
WHERE iCGM.ItemId = M.ItemId
ORDER BY iC.name
FOR XML PATH(''))
FROM Item M
So, it's the subquery what's failing for me. Any help would be much appreciated!