The first problem you are facing is that SqlServer
doesn't have an equivalent of MySql's GROUP_CONCAT
, nor does it have a generic aggregate Fold
capability.
So you'll need to use one of these hacks to get the comma delimited list of stock, e.g. STUFF / FOR XML PATH
:
SELECT Store, Artist,
STUFF((SELECT ',' + CAST(albumID AS VARCHAR(10))
FROM #AlbumStock a
WHERE a.Store = x.Store AND a.Artist = x.Artist
FOR XML PATH ('')), 1, 1, '') AS Stuffed
FROM
(
SELECT Store, artist
FROM #AlbumStock
GROUP BY Store, Artist
) x;
Which results in this:
Store Artist Stuffed
----------- --------------------------------
Glasgow Mission of burma 1
Glasgow Nirvana 1,4
Glasgow Wipers 3
Leeds Nirvana 1,2
Leeds Wipers 3,2
Manchester Wipers 3,2,1,4
To transform this with each Artist as a Column, you'll need a PIVOT
WITH cteStuffed AS
(
SELECT Store, Artist,
STUFF((SELECT ',' + CAST(albumID AS VARCHAR(10))
FROM AlbumStock a
WHERE a.Store = x.Store AND a.Artist = x.Artist
FOR XML PATH ('')), 1, 1, '') AS Stuffed
FROM
(
SELECT Store, artist
FROM AlbumStock
GROUP BY Store, Artist
) x
)
SELECT Store, [Mission of burma], [Wipers], [Nirvana]
FROM
cteStuffed
PIVOT
(
MIN(Stuffed)
for [Artist] IN ([Mission of burma], [Wipers], [Nirvana])
)pvt;
This then gives you the table you need, although I guess there are a couple of loose ends:
- You might want to use
ISNULL
orCOALESCE
to replace the NULLs with Zeroes. - You will probably want to determine the columns dynamically from the data. To do this, you'll need to resort to dynamic Sql - have a look at how BlueFeet does this here