2017-06-13 759 views
0

我有表,看起來像:如何在PostgreSQL中進行分組時使用三元運算符?

| name | feature | 
|------|---------| 
| bob | t  | 
| bob | f  | 

name是一個文本列和feature是一個布爾值。我想運行一個查詢,以便如果某個名稱的t存在於其相應的特徵值中,則該名稱將被分配爲t,否則爲f。喜歡的東西

SELECT name, CASE WHEN 't' in ARRAY_AGG(feature) THEN 't' ELSE 'f' END AS custom_feature 
FROM table 
GROUP BY name 

因此產生:

| name | custom_feature | 
|------|----------------| 
| bob | t    | 

什麼是Postgres而言,要做到這一點,最好的方法是什麼?

回答

0

如果我理解正確的,你需要的是這樣的:

select distinct on(name) name, feature 
from table 
order by name, feature desc 

如果功能欄爲空,那麼您可以:

select distinct on(name) name, coalesce(feature, false) 
from table 
order by name, feature desc nulls last 
3

有布爾聚集bool_and() and bool_or()

你可以寫你的查詢是這樣的:

SELECT name, bool_or(feature) AS custom_feature 
FROM my_table 
GROUP BY name; 
+0

哦,那很好。 –