简体   繁体   中英

Conditional branch in Postgres

I have a table defined as

CREATE TABLE public.area
(
    id INT,
    type VARCHAR(45)
);

Then I performed the following SQL :

WITH type_area AS (
    SELECT type
    FROM area
    WHERE area.id = 300
  GROUP BY type
)

From the type_area I have a set of distinct type. Now if the set contains only one type, I need to return that type, otherwise 'Multi_type' will be returned.

For example: The type_area only have one row, the value is 'Meeting' so 'Meeting' is returned. Otherwise 'Multi_type' is returned as the query result. I tried :

SELECT CASE WHEN count(type) > 1 THEN 'Multi_type'
       ELSE type
       END
FROM type_area

But I need to group by type again which leads to wrong result.

A simple solution would be to use an aggregate function everywhere, like

CASE WHEN count(type) > 1
     THEN 'Multi_type'
     ELSE max(type)
END

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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