sql - 在单个列上进行复杂选择

标签 sql postgresql

我有这张 table

create table customers(id int, cust text, email id, cust_grp int);

我使用以下选择查询在 3 种不同的条件下获得 3 个结果

select count(*) as cust_with_email 
from customers where email<>'' and cust_grp=101;

result
--------
199

select count(*)  as cust_without_email  
from customers where email='' and cust_grp=101;
result
--------
3370

select count(*)  as cust_total 
from customers where  cust_grp=101;
result
--------
3569

但现在我需要将这三个查询组合成一个选择,预期的输出是:

 custemaildet
---------------------
3569|199|3370

最佳答案

您可以使用 case when过滤 email column 并使用 | 符号连接结果

SELECT count(*) || '|' || count(CASE 
            WHEN email <> ''
                THEN email
            END) || '|' || count(CASE 
            WHEN email = ''
                THEN email
            END) custemaildet
FROM customers 
WHERE cust_grp= 101

关于sql - 在单个列上进行复杂选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30166078/

相关文章:

c# - 如何在 Dapper 中进行批量选择?

mysql - 如果我将 "UNIQUE"约束应用于列,数据库引擎是否会遍历整个表从而影响性能?

postgresql - 如何分析 PostgreSQL 数据库?

java - 在 postgresql 中以范围类型保存 Java 对象

mysql - 插入..选择,同一列不同值

mysql 2表连接未知列

sql - 选择返回最后一天的结果,周一不返回周五

sql - 将连接与 ORDER BY 相结合

postgresql - 从 postgis 中的查询插入表单

postgresql - Postgres 表选择查询太慢