【问题标题】:SQL | combining the results of two queries into one tableSQL |将两个查询的结果合并到一张表中
【发布时间】:2020-05-01 00:28:08
【问题描述】:
我是 SQL 新手......
我有一个表格,其中的一列“状态”包含已批准/已拒绝订单的列表。如何编写一个查询,在一个表中给出两列的结果:“总批准订单”、“总订单”?
我知道如何在两个单独的查询中提取这些结果,即:
SELECT COUNT(status) FROM orders WHERE status = 'Approved';
SELECT COUNT(status) FROM orders;
但不确定如何为一个表/结果完成此操作
【问题讨论】:
标签:
sql
group-by
count
pivot
【解决方案1】:
你可以做条件聚合:
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
【解决方案2】:
您可以将这些组合为子查询,如下所示;
SELECT
(SELECT COUNT(status) FROM orders WHERE status = 'Approved') AS 'Approved',
(SELECT COUNT(status) FROM orders) AS 'All Orders
;