这样可以更容易地在多行中将其列为项目,商店,当前库存。照原样,除非您知道商店的数量,否则将需要使用动态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) xpivot ( max(currentstock) for shop_name in ([Shop1],[Shop2])) p
- sqlfiddle
这是动态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)
- sqlfiddle
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)