简体   繁体   English

在SQL Postgres中按组进行迭代

[英]Iterate over group by in SQL Postgres

Starting with the end goal, I want a result set looking like the following: 从最终目标开始,我希望结果集如下所示:

name  | completed
_________________
Josh  |  T
Tom   |  T
Harry |  F

I have a table that looks like: 我有一张桌子,看起来像:

id | name | status
__________________
1    Josh   complete
2    Josh   errored
3    Tom    generating
4    Tom    complete
5    Harry  pending

As you can see from the result set, I want to know for each person whether they have ever had a status of complete. 从结果集中可以看到,我想让每个人都知道自己是否有完整的状态。 I think I want to iterate over each row in the grouped by clause checking status = 'complete' but I am struggling to do so. 我想我要遍历检查条件status = 'complete' by子句分组的每一行,但是我很努力。

You can do aggregation : 您可以进行聚合:

select name, coalesce(max(case when status = 'complete' then T end), 'F') as completed
from table t
group by name;

You could use the bool_or aggregate function : 您可以使用bool_or聚合函数

SELECT name, bool_or(status = 'complete')
FROM test
GROUP BY name

yields 产量

| name  | bool_or |
|-------+---------|
| Tom   | t       |
| Josh  | t       |
| Harry | f       |

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM