gpt4 book ai didi

SQL Server : Count the number of times the ID from table A occurs in table B

转载 作者:行者123 更新时间:2023-12-02 11:51:56 28 4
gpt4 key购买 nike

我有两个表:产品和订单。订单通过 ProductID 作为外键引用产品。我想知道每种产品已售出多少次,包括只售出一次的产品。我几乎可以使用左连接使其工作,但这仍然会为所有产品提供一行计数为 1 的产品,无论它们是否存在于订单表中。

有没有一种方法可以让你得到这样的结果?

Product | Times sold
Milk | 5
Bread | 18
Cheese | 0

...等等。

最佳答案

如果您只是执行 COUNT(*),那么您会将没有订单的产品计数为 1...而不是 COUNT(o.OrderID) ,它只会计算具有非空 OrderID 的记录。

SELECT p.Product, COUNT(o.OrderID)
FROM
Products p LEFT JOIN
Orders o ON o.ProductID = p.ProductID
GROUP BY p.Product

关于SQL Server : Count the number of times the ID from table A occurs in table B,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9067640/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com