我想知道我的答案是否适用于这个问题?我在互联网上找到的答案似乎很相似,但他们加入了另一张似乎模棱两可的表格。
问题:“单件定单”是指只订购一件商品的顾客定单。显示每个项目订单的SalesOrderID和UnitPrice。
他们的回答是:
select sod.SalesOrderID, sod.UnitPrice
from SalesLT.SalesOrderDetail sod
inner join SalesLT.SalesOrderHeader soh on soh.SalesOrderID =
sod.SalesOrderID
where sod.SalesOrderID in (
select s.SalesOrderID as ordernums
from SalesLT.SalesOrderDetail s
group by s.SalesOrderID
having COUNT(*) = 1
);我的答案是:
SELECT SalesOrderID, UnitPrice
FROM SalesOrderDetail
GROUP BY SalesOrderID
HAVING COUNT(SalesOrderID) = 1;发布于 2019-02-05 16:29:47
如果您运行您的答案,您将得到一个错误,因为UnitPrice不在GROUP BY中。如果添加它,您的HAVING将无法工作。
解决办法很简单。。。您需要一个聚合函数:
SELECT SalesOrderID, MAX(UnitPrice) as UnitPrice
FROM SalesOrderDetail
GROUP BY SalesOrderID
HAVING COUNT(SalesOrderID) = 1;https://stackoverflow.com/questions/54538758
复制相似问题