SQL Server:计算表A中的ID在表B中出现的次数
我有两个表:产品和订单。订单通过 ProductID 作为外键引用产品。我想知道每种产品已售出多少次,包括只售出一次的产品。我几乎可以使用左连接使其工作,但这仍然会为所有产品提供一行计数为 1 的产品,无论它们是否存在于订单表中。
有没有办法做到这一点,让你最终得到这样的结果?
Product | Times sold
Milk | 5
Bread | 18
Cheese | 0
... 等等。
I have two tables: products and orders. Orders references products via ProductID as a foreign key. I want to know how many times each product has been sold, including the product being sold only once. I can almost get it to work using a left join, but that still gives one row with a count of one for all products, regardless of whether they exist in the orders table or not.
Is there a way to do this that will have you ending up with something like this?
Product | Times sold
Milk | 5
Bread | 18
Cheese | 0
... and so on.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您只执行
COUNT(*)
,那么您会将没有订单的产品计数为 1...,而不是COUNT(o.OrderID)
,这将只计算具有非空OrderID
的记录。If you just do a
COUNT(*)
, then you're counting products that have no orders as 1... instead,COUNT(o.OrderID)
, which will only count the records that have a non-nullOrderID
.@迈克尔是正确的。
如果您有一个带有计数的订单表,它将如下所示:
@Michael is correct.
If you have an order table with a count it would look like this:
像这样的东西
Something like