SELECT: Group by function result

让人想犯罪 __ 提交于 2019-12-13 04:05:36

问题


I have a stored function that calculates the status of an entity (this status is NOT an attribute of the entity but needs to be calculated).
Within a SELECT statement, I want to know how many elements have which status.

For now, I got the following:

SELECT   my_function(entity_id) AS status,
         COUNT(*)
FROM     some_table
GROUP BY my_function(entity_id) -- entity_id is a column of some_table
ORDER BY status;

This works but I find it quite ugly to repeat the function call within the GROUP BY statement.
The code above is just an example. The actual function is defined within a package and has several input parameters.

Is it possible to do this without refering to the stored function within the GROUP BY statement?


回答1:


You can wrap your query in an external one to isolate the function call and use an alias:

select count(*),
       status
from ( 
        select s.*,
               my_function(entity_id) as status
        from some_Table s
     )
group by status
order by status


来源:https://stackoverflow.com/questions/52080167/select-group-by-function-result

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