gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 14:09:26 24 4
gpt4 key购买 nike

我有三个表 TableA、TableB、TableC,它们都通过 ID 链接。表 A 有 logTime,表 B 有 detectionTime,表 C 有 emptId。

对于我想要的每个 empId 1. tableB中没有detectionTime时logTime的计数 2. logTime和detectionTime差的平均值,如果找到detectionTime。

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

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

这里我在 blocked_time>0 平均值和其他统计数据时获得了条目。

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

最佳答案

首先,几点意见:

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

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

你要找的表达式是

count(blocked_time) FILTER (WHERE blocked_time = 0)

关于sql - 如何在 group by 子句中支持两个条件(postgresql),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47544710/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com