我有两个SQL查询可以自己正常工作但不是当我尝试将它们组合在一起时,很可能是我身边的一个基本误解。这些是查询;第三是我试图将它们结合起来。我错过了什么?我达到了很高的数量:Q1 / db1:185 Q2 / db2:180(这没关系,我正在编写查询来查找差异。)Q3:db1:925 db2:2340分别给出5和13乘数。
注意:Item_ID和ArticleNo是我语言的不同版本中的文本字段,因此是COLLATE DATABASE_DEFAULT。它们确实包含相同的信息。 在SQL Server 2008 R2上运行
我对dbo名称进行了一些匿名化。
SELECT CONVERT(INT, ROUND(SUM(i.Quantity), 0)) AS CUB,
i.Item_ID
FROM [dbo].[ITEM_CONFIGS] AS i
LEFT OUTER JOIN [dbo].[LOCATIONS_CONFIGS] AS l ON l.Config_ID = i.Config_ID
LEFT OUTER JOIN [dbo].[ITEMS] AS ii ON i.Item_ID = ii.Item_ID
WHERE i.Quantity > -1
GROUP BY i.Item_ID
ORDER BY i.Item_ID ASC
SELECT SUM(s.UnitInStock) AS UnitInStock,
s.ArticleNo
FROM [dbo].TotalsView AS s
LEFT OUTER JOIN [dbo].Article AS a ON s.ArticleNo = a.ArticleNo
LEFT OUTER JOIN [dbo].Supplier AS r ON a.MainSupplierNo = r.SupplierNo
WHERE s.ArticleNo IS NOT NULL
AND s.UnitInStock IS NOT NULL
AND a.InActiveYesNo = 0
GROUP BY s.ArticleNo
ORDER BY s.ArticleNo ASC
SELECT CONVERT(INT, ROUND(SUM(i.Quantity), 0)) AS CUB,
SUM(s.UnitInStock) AS UnitInStock,
s.ArticleNo
FROM [dbo].[ITEM_CONFIGS] AS i
LEFT JOIN [dbo].[LOCATIONS_CONFIGS] AS l ON l.Config_ID = i.Config_ID
LEFT JOIN [dbo].[ITEMS] AS ii ON i.Item_ID = ii.Item_ID
INNER [dbo].StockSurveyTotalsView AS s ON ii.Item_ID COLLATE database_default =
s.ArticleNo COLLATE database_default
INNER JOIN [dbo].Article AS a ON s.ArticleNo = a.ArticleNo
WHERE s.ArticleNo IS NOT NULL
AND s.UnitInStock IS NOT NULL
AND a.InActiveYesNo = 0
AND ii.Item_ID IS NOT NULL
GROUP BY s.ArticleNo
ORDER BY s.ArticleNo ASC
答案 0 :(得分:0)
使用相同的前2个查询作为CTE并加入它们以获得结果。
;WITH CUB AS (
SELECT CONVERT(INT, ROUND(SUM(i.Quantity), 0)) AS CUB,
i.Item_ID
FROM [dbo].[ITEM_CONFIGS] AS i
LEFT OUTER JOIN [dbo].[LOCATIONS_CONFIGS] AS l ON l.Config_ID = i.Config_ID
LEFT OUTER JOIN [dbo].[ITEMS] AS ii ON i.Item_ID = ii.Item_ID
WHERE i.Quantity > -1
GROUP BY i.Item_ID
),
UnitInStock AS (
SELECT SUM(s.UnitInStock) AS UnitInStock,
s.ArticleNo
FROM [dbo].TotalsView AS s
LEFT OUTER JOIN [dbo].Article AS a ON s.ArticleNo = a.ArticleNo
LEFT OUTER JOIN [dbo].Supplier AS r ON a.MainSupplierNo = r.SupplierNo
WHERE s.ArticleNo IS NOT NULL
AND s.UnitInStock IS NOT NULL
AND a.InActiveYesNo = 0
GROUP BY s.ArticleNo
)
SELECT c.CUB, uis.UnitInStock, uis.ArticleNo FROM CUB AS c
INNER JOIN UnitInStock AS uis ON c.Item_Id COLLATE database_default = uis.ArticleNo COLLATE database_default
ORDER BY uis.ArticleNo;
答案 1 :(得分:0)
在第三个查询中,您忘记在第一个查询中实施GROUP BY i.Item_ID
行。我会使用张鹏的CTE,因为它们更容易阅读/理解,但这就是为什么他应该工作的原因,而你的可能不会。