如何计算sql中where语句中的行数?

How to calculate rows count in where statement in sql?

我在 SQL 服务器中有两个表:

我想获取所有包含两个以上属性的订单:

  1. is_pay为1的行数:

     where payment_id = <...> payment.is_pay = 1
    
  2. 以及行数(没有第一个过滤器)

     select count(*) 
     from payment 
     where payment_id = <...>
    

所以我写了这个查询:

select 
    *, 
    (select count(1) from payment p 
     where p.payment_id = o.payment_id and p.is_pay = 1) as total 
from 
    order o

问题是如何计算没有 is_pay = 1 的行?

我的意思是“很多中的一些”

如果您要查找每个付款 ID 的计数,请使用此:

    select 
    payment.payment_id,
    count(*) as total,
    count(case when payment.is_pay = 1 then 1 else 0) end as total_is_pay_orders
    
    from orders
    left join payment
    on orders.payment_id = payment.payment_id
group by 1

使用带条件聚合的连接:

SELECT
    o.payment_id,
    COUNT(CASE WHEN p.is_pay = 1 THEN 1 END) AS pay_cnt,
    COUNT(p.payment_id) AS all_cnt
FROM "order" o
LEFT JOIN payment p
    ON o.payment_id = p.payment_id
GROUP BY
    o.payment_id;

先在payment聚合,然后加入order

SELECT o.*, p.total_pay, p.total
FROM [order] o 
LEFT JOIN (
  SELECT payment_id, SUM(is_pay) total_pay, COUNT(*) total
  FROM payment
  GROUP BY payment_id
) p ON p.payment_id = o.payment_id;

LEFT 更改为 INNER 如果所有订单至少有 1 次付款,则加入。
另外,如果is_pay的数据类型是BIT,把SUM(is_pay)改成:

SUM(CASE WHEN is_pay = 1 THEN 1 ELSE 0 END)

您可以为此使用横向连接 (outer apply):

select o.*, p.*
from orders o outer apply
     (select count(*) as num_payments,
             sum(case when is_pay = 1 then 1 else 0 end) as num_payments_1
      from payments p
      where p.payment_id = o.payment_id
     ) p;

注意:假设 is_pay 只取 01 的值(从名字来看这似乎是合理的),你可以将其简化为:

select o.*, p.*
from orders o outer apply
     (select count(*) as num_payments,
             sum(is_pay) as num_payments_1
      from payments p
      where p.payment_id = o.payment_id
     ) p;