如何计算sql中where语句中的行数?
Posted
技术标签:
【中文标题】如何计算sql中where语句中的行数?【英文标题】:How to calculate rows count in where statement in sql? 【发布时间】:2021-11-02 19:12:12 【问题描述】:我在 SQL Server 中有两个表:
order
(列:order_id
、payment_id
)
payment
(列:payment_id
、is_pay
)
我想获取所有带有另外两个属性的订单:
is_pay
为 1 的行数:
where payment_id = <...> payment.is_pay = 1
以及行数(没有第一个过滤器)
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 的行?
我的意思是“许多中的一些”
【问题讨论】:
示例数据在这里会有所帮助。 【参考方案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
【讨论】:
【参考方案2】:使用带有条件聚合的连接:
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;
【讨论】:
【参考方案3】:先聚合在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;
如果所有订单至少有 1 笔付款,请将 LEFT
更改为 INNER
加入。
另外,如果is_pay
的数据类型是BIT
,把SUM(is_pay)
改成:
SUM(CASE WHEN is_pay = 1 THEN 1 ELSE 0 END)
【讨论】:
【参考方案4】:您可以为此使用横向连接 (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
只接受 0
和 1
的值(这似乎是合理的名称),您可以将其简化为:
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;
【讨论】:
以上是关于如何计算sql中where语句中的行数?的主要内容,如果未能解决你的问题,请参考以下文章