I want to create an SQL report that shows an ordered stock list for a chain of record stores to show the current stock status of each: Nirvana, Mission of Burma and Wipers album, assuming each store only contains one album at any given time (for the sake of simplicity).
My SQL query currenty only shows whether or not each band has an album in stock I want to be able to show the stock level of every album so I think that I require some sort of nested return and possibly to use a pivot-table instead of Left Outer Joins.
Drop table #AlbumStock
Drop table #MissionOfBurma
Drop table #Wipers
Drop table #Nirvana
go
CREATE TABLE #AlbumStock
( Store varchar(Max),
Artist varchar(Max),
Album varchar(Max),
AlbumID int
)
go
INSERT INTO #AlbumStock
(Store,Artist,Album,AlbumID)
VALUES
('Glasgow','Wipers', 'Over the Edge', 3),
('Glasgow', 'Nirvana', 'Bleach', 1),
('Glasgow', 'Nirvana', 'Unplugged In New York', 4),
('Glasgow', 'Mission of burma', 'VS', 1),
('Leeds', 'Wipers', 'Over the Edge', 3),
('Leeds','Wipers', 'Youth of America', 2),
('Leeds', 'Nirvana', 'Bleach', 1),
('Leeds', 'Nirvana', 'Nevermind', 2),
('Manchester', 'Wipers', 'Over the Edge', 3),
('Manchester', 'Wipers', 'Youth of America', 2),
('Manchester', 'Wipers', 'Is this real?', 1),
('Manchester', 'Wipers', 'Land of the lost', 4)
Select MAX(AlbumID) As FirstID, Store
Into #MissionOfBurma
From #AlbumStock
Where Artist = 'Mission of burma'
Group BY Store
Select MAX(AlbumID) As FirstID, Store
Into #Wipers
From #AlbumStock
Where Artist = 'Wipers'
Group BY Store
Select MAX(AlbumID) As FirstID, Store
Into #Nirvana
From #AlbumStock
Where Artist = 'Nirvana'
Group BY Store
-- Current Reporting Query
Select stock.Store, ISNULL(mob.FirstID,0) As Mission_of_Burma_ID,
ISNULL(wip.FirstID,0) As Wipers_ID, ISNULL(nir.FirstID,0) As Nirvana_ID
From (Select Store
From #AlbumStock
Group BY Store ) as stock
LEFT OUTER JOIN
#MissionOfBurma as mob
ON
mob.Store = stock.Store
LEFT OUTER JOIN
#Wipers as wip
ON
wip.Store = stock.Store
LEFT OUTER JOIN
#Nirvana as nir
ON
nir.Store = stock.Store
The output from the query is this:
╔════════════╦═════════════════════╦═══════════╦════════════╗ ║ Store ║ Mission_of_Burma_ID ║ Wipers_ID ║ Nirvana_ID ║ ╠════════════╬═════════════════════╬═══════════╬════════════╣ ║ Glasgow ║ 1 ║ 3 ║ 4 ║ ║ Leeds ║ 0 ║ 3 ║ 2 ║ ║ Manchester ║ 0 ║ 4 ║ 0 ║ ╚════════════╩═════════════════════╩═══════════╩════════════╝
And I would like it to be something more like this:
╔════════════╦═════════════════════╦═══════════╦════════════╗ ║ Store ║ Mission_of_Burma_ID ║ Wipers_ID ║ Nirvana_ID ║ ╠════════════╬═════════════════════╬═══════════╬════════════╣ ║ Glasgow ║ 1 ║ 3 ║ 1 ║ 4 ║ ║ Leeds ║ 0 ║ 2 ║ 3 ║ 1 ║ 2 ║ ║ Manchester ║ 0 ║1 ║ 2║ 3║4 ║ 0 ║ ╚════════════╩═════════════════════╩═══════════╩════════════╝
Any advice/guidance would be greatly appreciated.