Multiplying two columns which have been calculated on a CASE statement

倾然丶 夕夏残阳落幕 提交于 2019-12-02 03:37:47

问题


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

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) newcol3
FROM table
GROUP BY newcol1,newcol2,newcol3

I need a fourth column which has to be the result of newcol2 * newcol3, how can I do that?

If I put (newcol2 * newcol3) AS newcol4 I get a syntax error.


回答1:


You can always use a CTE to abstract things away to a different level, if that helps - something along the lines of ...

With CTE as
(
 SELECT
  CASE column1
    WHEN something THEN 10
    ELSE 20
    END AS newcol1,
  CASE column12
    WHEN something THEN 30
    ELSE 40
    END AS newcol2,
  column3,
 FROM table
)
SELECT
  newcol1, newcol2,
  count(column3) as newcol3,
 (newcol2 * newcol3) AS newcol4
FROM CTE 
GROUP BY newcol1,newcol2,newcol3



回答2:


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.



来源:https://stackoverflow.com/questions/15437704/multiplying-two-columns-which-have-been-calculated-on-a-case-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!