[英]Combining the results of two SQL queries into one table but not with a union
[英]SQL | combining the results of two queries into one table
我是 SQL 的新手......
我有一个表格,其中一列“状态”包含已批准/已拒绝订单的列表。 如何编写一个查询,在一个表中给出两列的结果:“总批准订单”、“总订单”?
我知道如何在两个单独的查询中提取这些结果,即:
SELECT COUNT(status) FROM orders WHERE status = 'Approved';
SELECT COUNT(status) FROM orders;
但不确定如何为一张表/结果完成此操作
您可以进行条件聚合:
select
sum(case when status = 'Approved' then 1 else 0 end) total_orders_approved,
count(*) total_orders
from orders
根据您的数据库,可能会有更短的语法可用。 在 MySQL 中:
select
sum(status = 'Approved') total_orders_approved,
count(*) total_orders
from orders
在 Postgres 中:
select
Count(*) filter(where status = 'Approved') total_orders_approved,
count(*) total_orders
from orders
您可以将这些组合为子查询,如下所示;
SELECT
(SELECT COUNT(status) FROM orders WHERE status = 'Approved') AS 'Approved',
(SELECT COUNT(status) FROM orders) AS 'All Orders
;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.