Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SQL Server查询中的User COUNT()独立于where子句_Sql_Sql Server_Group By - Fatal编程技术网

SQL Server查询中的User COUNT()独立于where子句

SQL Server查询中的User COUNT()独立于where子句,sql,sql-server,group-by,Sql,Sql Server,Group By,我正在尝试使用SQL server中的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

我正在尝试使用SQL server中的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

顺便说一句,您绝对不需要
完全外部联接
。如果您的表设置了正确的外键关系,那么
内部
联接就足够了。您是否真的有订单,
CustomerId
字段在
users
中不是有效值?

不要忘记将其标记为正确答案@Milan4e