复杂选择单个列

时间:2015-05-11 11:06:24

标签: sql postgresql

我有这张桌子

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

3 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

使用条件聚合:

select count(*)  as cust_total,
       sum(case when email = '' then 1 else 0 end) as cust_without_email ,
       sum(case when email <> '' then 1 else 0 end)  as cust_with_email    
from customers
where cust_grp = 101

如果你想要一个列,那么你可以将它们连在一起:

select concat(count(*), '|',  
              sum(case when email = '' then 1 else 0 end), '|', 
              sum(case when email <> '' then 1 else 0 end)
             )    
from customers
where cust_grp = 101

答案 2 :(得分:0)

试试这个:

SELECT count(*), count(email = '' OR NULL), count(email <> '' OR NULL)
FROM customers
WHERE cust_grp = 101;

或者,在PG 9.4 +:

SELECT
    count(*),
    count(*) FILTER (WHERE email = ''),
    count(*) FILTER (WHERE email <> '')
FROM customers
WHERE cust_grp = 101;