我正在使用 MS SQL Server Management Studio 2008。我在编写子查询时遇到问题。这是整个查询如下:
SELECT DISTINCT
FH.ShipDate, AVG(FH.[Dist Freight]) AS [Atlantic Freight Charge],
(SELECT DISTINCT [Non-Atlantic Freight Charge]
FROM
(SELECT DISTINCT
FH.ShipDate, AVG(FH.[Dist Freight]) AS [Non-Atlantic Freight Charge]
FROM dbo.vw_FreightHistory AS FH
WHERE VendorName != 'Atlantic Trucking'
GROUP BY ShipDate, VendorName) AS [Non-Atlantic Freight Charge])
FROM dbo.vw_FreightHistory as FH
WHERE VendorName = 'Atlantic Trucking'
GROUP BY ShipDate, VendorName
ORDER BY ShipDate
问题首先出现在我添加第二个子查询时。第一个子查询没有返回任何错误,但它显示了每个 ShipDate 记录中“Dist Freight”的全部平均总和,而不是仅显示该 ShipDate 的平均值。我写了第二个子查询来尝试修复它,但现在我收到了这个错误:
Msg 512, Level 16, State 1, Line 1
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
如果我需要澄清任何事情,请告诉我。
最佳答案
我想你想要的是这样的:
SELECT
FH.ShipDate,
AVG(CASE
WHEN VendorName = 'Atlantic Trucking'
THEN FH.[Dist Freight]
ELSE NULL
END) AS [Atlantic Freight Charge],
AVG(CASE
WHEN VendorName != 'Atlantic Trucking'
THEN FH.[Dist Freight]
ELSE NULL
END) AS [Non-Atlantic Freight Charge]
FROM
dbo.vw_FreightHistory as FH
GROUP BY
ShipDate
ORDER BY
ShipDate
关于sql - "Subquery returned more than 1 value"用于 SELECT 子查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17750763/