谁能告诉我如何解决这个问题?
这是我的代码
子查询:
SELECT
A.StoreNo, C.[date], A.ProductBarCode, A.ProductQty
INTO
##inv1
FROM
#calender C
OUTER APPLY
(SELECT TOP 100 PERCENT *
FROM ##Temp I
WHERE I.Date < C.DATE
AND StoreNo IN (SELECT StoreNo FROM ##StoreList)
ORDER BY I.Date) A
OPTION (maxrecursion 0)
我使用前100%,因为每个商店都有超过1000个productBarcode,如果我选择前1,它第二天只显示一个productBarcode重复值。
Declare
@pheader nvarchar(Max), @sql_pivot nvarchar(max)
Begin
SELECT
@pheader = STUFF((SELECT distinct ',' + QUOTENAME([StoreNo])
FROM ##StoreList
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
--SET @pheader = LEFT(@pheader, LEN(@pheader) - 1)
SET @sql_pivot = 'SELECT *
FROM
(SELECT
S.[StoreNo], p.Date as Date,
p.ProductBarCode as ProductBarCode,
ISNULL(i.productqty - (SELECT ProductQty as runningsum
FROM #Stock st
WHERE st.date <= i.date
AND st.storeno = i.storeno
AND st.ProductBarCode = i.ProductBarCode), i.productqty) as ProductQty
FROM #inventory i
LEFT JOIN ##StoreList S ON S.StoreNo = i.StoreNo
LEFT JOIN #Stock st ON st.StoreNo = i.StoreNo AND st.ProductBarCode = i.ProductBarCode AND st.Date = i.Date
RIGHT JOIN ##product p ON i.Date = P.Date and p.ProductBarCode = i.ProductBarCode
-- where p.ProductBarCode IN(2300007115072,2300012213046,2300012712075)
GROUP BY S.storeNo, i.StoreNo, i.ProductBarCode, i.Date, p.ProductBarCode, p.Date, i.ProductQty) p
PIVOT (SUM(ProductQty)
FOR [StoreNo] IN ('+ @pheader+') )Pvt'
EXECUTE sp_executesql @sql_pivot
我一次不能获得三到四个商店如果我选择超过10个它显示此错误
子查询返回的值超过1。这是不允许的 子查询跟随=,!=,&lt;,&lt; =,&gt;,&gt; =或当子查询用作 表达。
我正在使用SQL Server。
答案 0 :(得分:0)
尝试按日期,地址或任何不重复的顺序排序查询。 Souns就像一个非常愚蠢的解决方案,但它在一个带有DESC计数的Access数据库中为我工作。
看起来如果在订单中重复值sql返回超过需要...我真的不知道为什么但它对我有用!
试试吧!
答案 1 :(得分:-1)
将前1添加到子查询中。试试这个,
DECLARE @pheader NVARCHAR(Max)
,@sql_pivot NVARCHAR(max)
BEGIN
SELECT @pheader = STUFF((
SELECT DISTINCT ',' + QUOTENAME([StoreNo])
FROM ##StoreList
FOR XML PATH('')
,TYPE
).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
SET @pheader = LEFT(@pheader, LEN(@pheader) - 1)
SET @sql_pivot =
'SELECT *
FROM
(SELECT
S.[StoreNo], p.Date as Date,
p.ProductBarCode as ProductBarCode,
ISNULL(i.productqty - (SELECT top 1 ProductQty as runningsum
FROM #Stock st
WHERE st.date <= i.date
AND st.storeno = i.storeno
AND st.ProductBarCode = i.ProductBarCode), i.productqty) as ProductQty
FROM #inventory i
LEFT JOIN ##StoreList S ON S.StoreNo = i.StoreNo
LEFT JOIN #Stock st ON st.StoreNo = i.StoreNo AND st.ProductBarCode = i.ProductBarCode AND st.Date = i.Date
RIGHT JOIN ##product p ON i.Date = P.Date and p.ProductBarCode = i.ProductBarCode
-- where p.ProductBarCode IN(2300007115072,2300012213046,2300012712075)
GROUP BY S.storeNo, i.StoreNo, i.ProductBarCode, i.Date, p.ProductBarCode, p.Date, i.ProductQty) p
PIVOT (SUM(ProductQty)
FOR [StoreNo] IN ('
+ @pheader + ') )Pvt'
EXECUTE sp_executesql @sql_pivot
END