我写了一个定义变量的脚本。
这样定义一个变量。
SET @Yesterday = (SELECT SUM (ri.Sales_Quantity)
FROM ReportTransactions AS RT
LEFT JOIN ReportItems AS ri ON rt.Report_Transaction_ID = ri.Report_Transaction_ID
LEFT JOIN MMGroups AS mmg ON ri.MMGroup2_ID = MMG.ID
LEFT JOIN Locations AS L ON L.Location_ID = RT.Store_ID
WHERE rt.Transaction_Date > DATEADD(DAY, -1, GETDATE())
AND (NULL IS NULL OR rt.Store_ID = NULL)
AND (rt.Training_Mode IS NULL OR rt.Training_Mode = 0)
AND ri.Item_Voided = 0
AND ri.Void_Type = 0
AND rt.Transaction_Type IN (0, 1, 2, 3, 4, 5, 6)
AND ri.Item_Type IN (1, 2, 3, 4, 6, 7, 54, 55, 81, 84, 11, 12, 13, 22, 25, 27, 82)
GROUP BY
RT.Store_ID);
但是它返回多个值,因此无法定义变量并引发错误。
我的报告需要所有这些行,所以如何定义它们并检索它们,最佳实践是什么?
答案 0 :(得分:0)
您需要表temporary
或base
是因为您想要多个行或列:
SELECT RT.Store_ID, SUM (ri.Sales_Quantity) AS Sum_Qty INTO #table
FROM ReportTransactions AS RT LEFT JOIN
ReportItems AS ri
ON rt.Report_Transaction_ID = ri.Report_Transaction_ID LEFT JOIN
MMGroups AS mmg
ON ri.MMGroup2_ID = MMG.ID LEFT JOIN
Locations AS L
ON L.Location_ID = RT.Store_ID
WHERE . . .
GROUP BY RT.Store_ID;
但是,基表需要INSERT INTO
语句和SELECT
语句:
INSERT INTO table (col1, col2)
SELECT . . . ;
答案 1 :(得分:0)
也许您可以尝试使用表变量。
DECLARE @Yesterday Table
(
Sum_Qty int
)
insert into @Yesterday
SELECT SUM (ri.Sales_Quantity)
FROM ReportTransactions AS RT
LEFT JOIN ReportItems AS ri ON rt.Report_Transaction_ID = ri.Report_Transaction_ID
LEFT JOIN MMGroups AS mmg ON ri.MMGroup2_ID = MMG.ID
LEFT JOIN Locations AS L ON L.Location_ID = RT.Store_ID
WHERE rt.Transaction_Date > DATEADD(DAY, -1, GETDATE())
AND (NULL IS NULL OR rt.Store_ID = NULL)
AND (rt.Training_Mode IS NULL OR rt.Training_Mode = 0)
AND ri.Item_Voided = 0
AND ri.Void_Type = 0
AND rt.Transaction_Type IN (0, 1, 2, 3, 4, 5, 6)
AND ri.Item_Type IN (1, 2, 3, 4, 6, 7, 54, 55, 81, 84, 11, 12, 13, 22, 25, 27, 82)
GROUP BY
RT.Store_ID