Multiplying two columns which have been calculated on a CASE statement

后端 未结 2 1655
礼貌的吻别
礼貌的吻别 2021-01-23 04:52

I am performing a SQL query in PostgreSQL using a CASE statement like this:

SELECT
    CASE column1
        WHEN something THEN 10
        ELSE 20
          


        
2条回答
  •  别那么骄傲
    2021-01-23 05:09

    A CTE is a valid approach, giving additional options.
    For a simple case like this a plain subquery is simpler and slightly faster.

    SELECT *, (newcol2 * newcol3) AS newcol4
    FROM  (
       SELECT CASE column1
                WHEN something THEN 10
                ELSE 20
                END AS newcol1
             ,CASE column12
                WHEN something THEN 30
                ELSE 40
                END AS newcol2
            ,COUNT(column3) AS newcol3
       FROM  table
       GROUP BY 1, 2
       ) AS sub
    

    BTW: I removed newcol3 from GROUP BY, since you are running the aggregate function count() on it, which is slightly nonsensical.

提交回复
热议问题