如何根据不同的条件在一个查询中对单个字段进行两次计数

时间:2017-11-03 15:22:53

标签: sql postgresql

我想计算两次相同的字段,根据另一个子查询的不同条件进行区分。伪代码将是这样的:

select countd(svc_ord_nbr) <if start_dt = end_dt> as fixed, 
       countd(svc_ord_nbr) <else> as unfixed
       from [subquery]

子查询基本上是根据相同的svc_ord_nbr获取活动日期的最小值和最大值

select svc_ord_nbr, date_part('day', min(e.START_DTM)) as start_dt,
    date_part('day', max(e.START_DTM)) as end_dt
    from order o join activity a on o.svc_activity_id = a.activity_id
    group by svc_ord_nbr

How to count same field twice based on a boolean中的答案表明在布尔值上做case when。但是,它没有考虑到明显的价值。有没有办法只为distanct值计算两次相同的字段。

2 个答案:

答案 0 :(得分:1)

您可以使用条件聚合:

select 
  count(DISTINCT CASE WHEN start_dt = end_dt THEN svc_ord_nbr END) as fixed, 
  count(DISTINCT CASE WHEN start_dt <> end_dt THEN svc_ord_nbr END )as unfixed
from [subquery];

或者使用窗口函数:

select DISTINCT
  count(DISTINCT svc_ord_nbr) FILTER(WHERE start_dt = end_dt) OVER() as fixed, 
  count(DISTINCT svc_ord_nbr) FILTER(WHERE start_dt <> end_dt) OVER() as unfixed
from [subquery];

如果需要,您可以在PARTITION BY内添加OVER

答案 1 :(得分:1)

您可以在聚合函数上使用filter

select count(distinct svc_ord_nbr) FILTER (WHERE start_dt = end_dt) as fixed, 
       count(distinct svc_ord_nbr) FILTER (WHERE start_dt <> end_dt) as unfixed
from [subquery];