Why can't I use an alias for an aggregate in a having clause?

后端 未结 8 1874
我在风中等你
我在风中等你 2020-12-02 14:26

My code is like shown below :

select col1,count(col2) as col7
from --some join operation
group by col1
having col7 >= 3 -- replace col7 by count(col2) to          


        
8条回答
  •  鱼传尺愫
    2020-12-02 15:00

    You can solve this by using a nested query.

    I have also run into this problem when I am wanting to improve performance. I have needed to run a count() based on certain fields within a JSON field in a table, obviously we would want to parse JSON only once instead of having to include a separate count in a where or have clause (especially an expensive one like in my case).

    If col1 is a unique id, the most computationally efficient way could be to nest the count in a separate select

    select col1, innerquery.col7
    from whatevertable
    inner join (select col1, count(col2) as col7 
                from whatevertable 
                group by col1) as innerquery 
                on innerquery.col1 = whatevertable.col1
    where innerquery.col7 >= 3;
    

    This way the count is only ran once, creating a sort of temporary lookup table for reference by the rest of your query.

    Again, this only works if col1 is unique for every record, which normally isn't too much to ask since most tables have some sort of id primary key.

提交回复
热议问题