Using CASE in PostgreSQL to affect multiple columns at once

后端 未结 2 1149
礼貌的吻别
礼貌的吻别 2021-02-01 04:16

I have a Postgres SELECT statement with these expressions:

,CASE WHEN (rtp.team_id = rtp.sub_team_id)
 THEN \'testing\'
 ELSE TRIM(rtd2.team_name)
          


        
2条回答
  •  滥情空心
    2021-02-01 04:30

    Not sure that it would be an improvement, but you could union the SELECT one way with itself the other way:

    SELECT 
      ...,
      'testing' AS testing_testing,
      'test example' AS test_response,
      'test example #2' AS another_example, ...
    FROM ...
    WHERE rtp.team_id = rtp.sub_team_id AND ...
    UNION 
    SELECT
      ...,
      TRIM(rtd2.team_name) AS testing_testing,
      TRIM(rtd2.normal_data) AS test_response,
      TRIM(rtd2.normal_data_2) AS another_example, ...
    WHERE rtp.team_id <> rtp.sub_team_id AND ...;
    

    The column names can safely be omitted from the second query, assuming you bring them out in the same order as in the first.

    You may want to make each of those a separate query using common table expressions (CTEs). If you're worried about this changing the order, you can make it a subquery and apply an ORDER BY around it.

提交回复
热议问题