这将更容易在多行中列为 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)