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

后端 未结 8 1881
我在风中等你
我在风中等你 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 14:52

    U can use this code:

    IF OBJECT_ID('tempdb..#temp') is not null DROP TABLE #temp
    
    -- Create tempurary table
    CREATE TABLE #temp (Id BIGINT IDENTITY(1,1), col1 BIGINT, countOfcol2 BIGIN)
    
    --insert from the table 2 #temp
    INSERT INTO #temp (col1,countOfcol2) 
    
    select col1,count(col2) as col7
    from --some join operation
    
    select col1,countOfcol2 from #temp
    group by col1
    having countOfcol2 >= 3 -- replace col7 by count(col2) to make the code work
    

提交回复
热议问题