SQL 服务器查询中的用户 COUNT() 独立于 where 子句

User COUNT() in SQL Server query to be independent on the where clause

我正在尝试使用 SQL 服务器中的 COUNT 函数来计算每个客户的订单数量,这与最后的条件无关。

    select u.FullName, u.Id, o.FullAddress, 
    Price, Payment, o.Created, StartDelivery as Delivering, 
    [Status], o.Id,

    (select COUNT(Orders.Id)
    from Orders 
    full outer join Users
    on Users.Id = Orders.CustomerId) as CountOfOrders

    from orders o
    full outer join users u
    on o.CustomerId = u.Id

    where [Status] = 0 and Payment = 1;

通过这个查询,我得到的似乎是订单总数,而且它的数量在每一行中。我想按客户分组,但不是基于最后的条件。我需要按客户分组的订单总数。

并使用此查询:

select u.FullName, u.Id, o.FullAddress, 
Price, Payment, o.Created, StartDelivery as Delivering, 
[Status], o.Id, COUNT(*) OVER (PARTITION BY o.CustomerId) AS CountOfOrders

from orders o
full outer join users u
on o.CustomerId = u.Id

where [Status] = 2;

订单数量是分组的,但根据最后的条件。无论最后的情况如何,我都需要按客户分组的订单总数。抱歉重复我自己我只是想确保我清楚 :)

非常感谢您对此的任何意见和您的宝贵时间!

您可以使用子查询:

select ou.*
from (select u.FullName, u.Id, o.FullAddress,
             Price, Payment, o.Created, StartDelivery as Delivering, 
             [Status], o.Id,
             COUNT(*) OVER (PARTITION BY o.CustomerId) AS CountOfOrders
      from orders o full outer join
           users u
           on o.CustomerId = u.Id
     ) ou
where [Status] = 2

顺便说一句,你绝对不需要full outer join。如果您的表设置了适当的外键关系,那么 inner 连接就足够了。您真的有 CustomerId 字段在 users 中不是有效值的订单吗?