If you are running SQL Server, you need to use something like this for group_concat mySQL http://archive.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=createacommadelimitedlist . MySQL's solution and one of them suggests that the order of the elements in each field is always the same or that the elements must be sorted before they are combined so that you can compare the contents of each window. It ends up looking pretty dirty with all the nesting, but it gives the desired result:
SELECT count(box) NumBoxes, list Contents, BoxList = substring((SELECT ( ', ' + cast(box as varchar) ) FROM (SELECT b1.box, List = substring((SELECT ( ', ' + item ) FROM boxes b2 WHERE b1.box = b2.box ORDER BY box, item FOR XML PATH( '' ) ), 3, 1000 ) FROM boxes b1 GROUP BY box ) source2 WHERE source1.list = source2.list ORDER BY box, list FOR XML Path( '' ) ), 3, 1000 ) FROM(SELECT b1.box, List = substring((SELECT ( ', ' + item ) FROM boxes b2 WHERE b1.box = b2.box ORDER BY box, item FOR XML PATH( '' ) ), 3, 1000 ) FROM boxes b1 GROUP BY box ) source1 GROUP BY list
By the way, I used this table for testing, and the fact that BOX was an INT data type required transfer in the third line of code above:
create table boxes( BOX int null, ITEM char(7) null) go insert into boxes values(1,'0000001'), (1,'0000002'), (1,'0000003'), (1,'0000004'), (2,'1111111'), (2,'1111111'), (2,'1111111'), (2,'1111111'), (3,'0000001'), (3,'0000002'), (3,'0000003'), (3,'0000004'), (4,'0000001'), (4,'0000002'), (4,'0000003') go