我是SQL Server新手。我想使用sum
函数等于两列。请找到以下查询。
select top 1000
o.orderamount, sum(oi.amount), oi.orderid
from
orders o
inner join
orderitem oi on o.orderid = oi.orderid
where
orderamount = sum(oi.amount)
group by
oi.orderid, orderamount
order by
oi.orderid desc
每当我执行此代码时,都会收到错误。
请帮帮我。
答案 0 :(得分:10)
您可以使用HAVING:
[1]
答案 1 :(得分:0)
您可以使用:
select top 1000 o.orderamount, oi.amount, oi.orderid
from orders o
inner join (select orderid, sum(amount) amount from orderitem group by orderid) orderitem
oi on o.orderid = oi.orderid and orderamount = oi.amount
order by oi.orderid desc
答案 2 :(得分:0)
在求和查询中尝试使用HAVING而不是WHERE子句。 另外:添加缩进和大写以提高可读性
SELECT TOP 1000 o.OrderAmount, sum(oi.Amount), oi.OrderID
FROM Orders o
INNER JOIN OrderItem oi ON oi.OrderID = o.OrderID
GROUP BY oi.OrderID, OrderAmount
HAVING OrderAmount = sum(oi.Amount)
ORDER BY oi.OrderID DESC;