複数の行に item、shop、currentstock としてリストする方が簡単です。そのままでは、ショップの数がわからない場合は、動的 SQL を使用する必要があります。潜在的なショップの数がわかっている場合は、 を使用PIVOT
して結果を返すことができます。
2 つのショップ (shop1 と shop2) があると仮定すると、次のようになります。
select item_name, [Shop1], [Shop2]
from
(
select item_name, shop_name, currentstock
from item i
join shopstock ss on i.item_id = ss.item_id
join shop s on s.shop_id = ss.shop_id
) x
pivot
(
max(currentstock)
for shop_name in ([Shop1],[Shop2])
) p
可能なショップの数がわからないので、動的SQLアプローチを次に示します。
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = stuff((select distinct ',' + quotename(shop_name)
from shop
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'select item_name,' + @cols + '
from
(
select item_name, shop_name, currentstock
from item i
join shopstock ss on i.item_id = ss.item_id
join shop s on s.shop_id = ss.shop_id
) x
pivot
(
max(currentstock)
for shop_name in (' + @cols + ')
) p '
execute(@query)