SQL - using alias in Group By

前端 未结 10 1648
不思量自难忘°
不思量自难忘° 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:49

    I'm not answering why it is so, but only wanted to show a way around that limitation in SQL Server by using CROSS APPLY to create the alias. You then use it in the GROUP BY clause, like so:

    SELECT 
     itemName as ItemName,
     FirstLetter,
     Count(itemName)
    FROM table1
    CROSS APPLY (SELECT substring(itemName, 1,1) as FirstLetter) Alias
    GROUP BY itemName, FirstLetter
    

提交回复
热议问题