我需要在PostgreSQL中的一个语句中获得以下两个查询。
select count(*) as REDEEMTOTALUSED
from voucher
where campaign_id='123' and redeemcount>0;
select count(*) as REDEEMTOTALUNUSED
from voucher
where campaign_id='123' and redeemcount=0;
结果如下:
REDEEMTOTALUSED | REDEEMTOTALUNUSED 1 | 9
这可能吗?
答案 0 :(得分:3)
请尝试:
select
(select count(*) as REDEEMTOTALUSED
from voucher
where campaign_id='123' and redeemcount>0) AS REDEEMTOTALUSED ,
(select count(*) as REDEEMTOTALUNUSED
from voucher
where campaign_id='123' and redeemcount=0) AS REDEEMTOTALUNUSED
或其他方式:
SELECT
SUM(CASE
WHEN redeemcount>0 THEN 1
ELSE 0
END) as REDEEMTOTALUSED ,
SUM(CASE
WHEN redeemcount=0 THEN 1
ELSE 0
END) as REDEEMTOTALUNUSED
from
voucher
WHERE
campaign_id='123'
答案 1 :(得分:2)
使用条件聚合:
select sum(case when redeemcount > 0 then 1 else 0 end) as REDEEMTOTALUSED,
sum(case when redeemcount = 0 then 1 else 0 end) as REDEEMTOTALUNUSED
from voucher
where campaign_id = '123';
答案 2 :(得分:1)
SELECT count(redeemcount > 0 OR NULL) AS redeemtotalused
, count(redeemcount = 0 OR NULL) AS redeemtotalunused
FROM voucher
WHERE campaign_id = '123'; -- or just 123 if campaign_id is a numeric type
适用技术概述:
除此之外:在Postgres(Overview)中,未加引号的标识符会强制转换为小写。你的语法约定在Postgres中是无用的。
答案 3 :(得分:0)
使用CTE还有另一个选项:
with cte as (
select count(*) as REDEEMTOTALUSED
from voucher
where campaign_id='123' and redeemcount>0
),cte1 as (
select count(*) as REDEEMTOTALUNUSED
from voucher
where campaign_id='123' and redeemcount=0
)
select REDEEMTOTALUSED
,REDEEMTOTALUNUSED
from
cte1,cte2