我使用子查询返回折扣大于15%的所有订单的货币值。 列出最后一个具有最高值
的orderid和订单值这是我输入的内容:
SELECT SUM(od.orderid) As OrderID,
AS [Order Values]
FROM [Order Details] od
WHERE od.Discount =
(SELECTod.Discount
FROM [Order Details] od
GROUP BY od.discount
HAVING od.discount >.15)
GROUP BY od.quantity, od.discount, od.UnitPrice
ORDER BY [Order Values] ASC;
这是我得到的:
Msg 512,Level 16,State 1,Line 1 子查询返回的值超过1。子查询遵循=,!=,<,< =,>,>时不允许这样做。 =>或者当子查询用作表达式时。
我错过了什么?
答案 0 :(得分:1)
错误在WHERE
子句中。您使用=
表示多个值,但该运算符仅允许1个值。所以改变这个:
WHERE od.Discount =
(SELECT od.Discount
FROM [Order Details] od
GROUP BY od.discount
HAVING od.discount >.15)
对此:
WHERE od.Discount IN
(SELECT od.Discount
FROM [Order Details] od
GROUP BY od.discount
HAVING od.discount >.15)
或者这个:
WHERE od.Discount =
(SELECT TOP 1 od.Discount
FROM [Order Details] od
GROUP BY od.discount
HAVING od.discount >.15
ORDER BY od.Discount DESC)
答案 1 :(得分:0)
使用WHERE IN
代替WHERE =
这应该处理子查询返回的多个值
SELECT SUM(od.orderid) As OrderID,
AS [Order Values]
FROM [Order Details] od
WHERE od.Discount IN
(SELECT od.Discount
FROM [Order Details] od
GROUP BY od.discount
HAVING od.discount >.15)
GROUP BY od.quantity, od.discount, od.UnitPrice
ORDER BY [Order Values] ASC;
答案 2 :(得分:0)
无论如何,你真的不需要子查询
SELECT OrderID, SUM(UnitPrice * Quantity) OrderTotal
FROM dbo.[Order Details]
WHERE Discount > 0.15
GROUP BY OrderID
ORDER BY OrderTotal DESC
使用子查询
SELECT OrderID, SUM(UnitPrice * Quantity) OrderTotal
FROM dbo.[Order Details]
WHERE OrderID IN (SELECT OrderID
FROM dbo.[Order Details]
WHERE Discount > 0.15)
GROUP BY OrderID
ORDER BY OrderTotal DESC
使用EXISTS运算符
SELECT OD.OrderID, SUM(OD.UnitPrice * OD.Quantity) OrderTotal
FROM dbo.[Order Details] OD
WHERE EXISTS (SELECT 1
FROM dbo.[Order Details]
WHERE OrderID = OD.OrderID
AND Discount > 0.15)
GROUP BY OD.OrderID
ORDER BY OrderTotal DESC