SQL - using alias in Group By

前端 未结 10 1801
不思量自难忘°
不思量自难忘° 2020-11-22 08:52

Just curious about SQL syntax. So if I have

SELECT 
 itemName as ItemName,
 substring(itemName, 1,1) as FirstLetter,
 Count(itemName)
FROM table1
GROUP BY it         


        
10条回答
  •  春和景丽
    2020-11-22 09:50

    Caution that using alias in the Group By (for services that support it, such as postgres) can have unintended results. For example, if you create an alias that already exists in the inner statement, the Group By will chose the inner field name.

    -- Working example in postgres
    select col1 as col1_1, avg(col3) as col2_1
    from
        (select gender as col1, maritalstatus as col2, 
        yearlyincome as col3 from customer) as layer_1
    group by col1_1;
    
    -- Failing example in postgres
    select col2 as col1, avg(col3)
    from
        (select gender as col1, maritalstatus as col2,
        yearlyincome as col3 from customer) as layer_1
    group by col1;
    

提交回复
热议问题