SQL - using alias in Group By

前端 未结 10 1642
不思量自难忘°
不思量自难忘° 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;
    
    0 讨论(0)
  • 2020-11-22 09:52

    Back in the day I found that Rdb, the former DEC product now supported by Oracle allowed the column alias to be used in the GROUP BY. Mainstream Oracle through version 11 does not allow the column alias to be used in the GROUP BY. Not sure what Postgresql, SQL Server, MySQL, etc will or won't allow. YMMV.

    0 讨论(0)
  • 2020-11-22 09:53

    You could always use a subquery so you can use the alias; Of course, check the performance (Possible the db server will run both the same, but never hurts to verify):

    SELECT ItemName, FirstLetter, COUNT(ItemName)
    FROM (
        SELECT ItemName, SUBSTRING(ItemName, 1, 1) AS FirstLetter
        FROM table1
        ) ItemNames
    GROUP BY ItemName, FirstLetter
    
    0 讨论(0)
  • 2020-11-22 09:57

    At least in PostgreSQL you can use the column number in the resultset in your GROUP BY clause:

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

    Of course this starts to be a pain if you are doing this interactively and you edit the query to change the number or order of columns in the result. But still.

    0 讨论(0)
提交回复
热议问题