如何在group by子句中支持两个条件(postgresql)

时间:2017-11-29 03:44:50

标签: sql postgresql

我有三个表TableA,TableB,TableC它们都是通过id链接的。表A有logTime,tableB有detectTime,TableC有emptId。

对于我想要的每个人     1.当tableB中没有找到detectionTime时的logTime计数     2.如果发现detectTime,则logTime和detectionTime的平均值。

我已经编写了这个查询,当查找到detectTime时获取平均值但不确定如何在找不到detectTime时获取数据

select det.empid  ,average(det.blocked_time) 
FROM (SELECT c.emplid as empid, EXTRACT(EPOCH FROM ( a.detectionTime - b.logTime )) as blocked_time
        ## inner and join condition here
  ) As det group by det.emplid where dat.blocked_time>0

这里我在封锁时间> 0平均值和其他统计数据时输入。

当blocked_time为0时,如何获取每个empId的blocked_time计数

3 个答案:

答案 0 :(得分:2)

首先,一些评论:

  • 您。 SQL语句在语法上是不正确的。 WHERE必须在GROUP BY之前。

  • 您的查询似乎假设id是所有三个表的唯一键。否则,相同的值可能会多次出现在连接结果中。

您正在寻找的表达式是

count(blocked_time) FILTER (WHERE blocked_time = 0)

答案 1 :(得分:1)

由于没有共享样本数据,因此(假设)选项可以在内部查询中使用left joincoalesceNULL的{​​{1}}值转换为detectionTime {1}}然后在外部查询中使用条件聚合,如下所示。

0

答案 2 :(得分:1)

试试这个:

select emptid,
sum(case when detectiontime is null then 1 else 0 end) as count,
average(case when detectiontime is not null then diff else 0 end) as avg
(
select a.*,b.detectiontime,c.emptid,a.logtime-b.detectiontime as diff
from
tablea a
left join
tableb b
on a.id = b.id
left join
tablec c
on a.id = c.id
)
group by emptid;

如果您正在寻找其他内容,请告诉我。