我有以下SQL查询
Select Product_Id, [riy] AS [riy],
[eas] AS [eas]
FROM
(SELECT Product_Id, Store_Name, Quantity
FROM [Product_Stock] INNER JOIN Store on Store.Id = [Product_Stock].Stock_Id where Product_Id = 435) ps
PIVOT
(
SUM(Quantity)
FOR Store_Name IN
([riy],[EAST WAREHOUSE - eas])
) AS pvt
它给出了预期的结果。给我位置riy和eas的总数量。
但是,我想动态获取商店名称,而不是手动指定它们。
这就是我所做的。
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
SELECT @cols = STUFF((SELECT ',' + QUOTENAME([Product_Id])
FROM [Product_Stock]
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
SELECT @query =
'SELECT Product_Id FROM
(SELECT Product_Id, Store_Name, Quantity
FROM [Product_Stock] INNER JOIN Store on Store.Id = [Product_Stock].Stock_Id where Product_Id = 435) PS
PIVOT
(
SUM(Quantity)
FOR Store_Name in (' + @cols + ')
) AS PVT'
EXEC SP_EXECUTESQL @query
这给我一个错误说 'PVT'多次指定了'638'列。
我该如何解决这个问题?
答案 0 :(得分:3)
在不知道您的实际数据的情况下,这是一次盲目飞行,但我认为您有两个问题:
DISTINCT
才能获得每个值试试这个
SELECT @cols = STUFF((SELECT DISTINCT ',' + QUOTENAME([Store_Name])
FROM [Product_Stock]
INNER JOIN Store on Store.Id = [Product_Stock].Stock_Id
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
答案 1 :(得分:2)
确保cols是DISTINCT
... STUFF((SELECT DISTINCT ','...
答案 2 :(得分:1)
感谢@Shnugo推动我朝着正确的方向前进。这是我最终使用的查询。
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
SELECT @cols = STUFF((SELECT DISTINCT ',' + QUOTENAME([Store].Store_Name)
FROM [Store] INNER JOIN Product_Stock ON Product_Stock.Stock_Id = Store.Id
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
SELECT @query =
'SELECT Product_Id , ' + @cols + ' from
(SELECT Product_Id, Store_Name, Quantity
FROM [Product_Stock] INNER JOIN Store on Store.Id = [Product_Stock].Stock_Id WHERE Product_Stock.product_id = 435 ) PS
PIVOT
(
SUM(Quantity)
FOR Store_Name in (' + @cols + ')
) AS PVT'
EXEC SP_EXECUTESQL @query