简体   繁体   English

SQL | 将两个查询的结果合并到一张表中

[英]SQL | combining the results of two queries into one table

I'm new to SQL....我是 SQL 的新手......

I have a table in which one column, "status", has a list of approved/declined orders.我有一个表格,其中一列“状态”包含已批准/已拒绝订单的列表。 How do I write a query that gives the result of two columns: 'Total Approved Orders', 'Total Orders' in one table?如何编写一个查询,在一个表中给出两列的结果:“总批准订单”、“总订单”?

I know how to pull these results in two separate queries, ie:我知道如何在两个单独的查询中提取这些结果,即:

SELECT COUNT(status) FROM orders WHERE status = 'Approved';

SELECT COUNT(status) FROM orders;

But unsure how this is done for one table/result但不确定如何为一张表/结果完成此操作

You can do conditional aggregation:您可以进行条件聚合:

select
    sum(case when status = 'Approved' then 1 else 0 end) total_orders_approved,
    count(*) total_orders
from orders

Depending on your database, there might be shorter syntaxes available.根据您的数据库,可能会有更短的语法可用。 In MySQL:在 MySQL 中:

select
    sum(status = 'Approved') total_orders_approved,
    count(*) total_orders
from orders

In Postgres:在 Postgres 中:

select
    Count(*) filter(where status = 'Approved') total_orders_approved,
    count(*) total_orders
from orders

You can combine these as sub queries as follows;您可以将这些组合为子查询,如下所示;

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM