重用别名SQL Server

时间:2016-07-19 18:06:47

标签: mysql sql-server

所以我试图完成这项任务在拥有前五大邮政编码的城市中,有多少邮政编码中包含字符串09?

我有以下内容可以找到最多的邮政编码

Select 
      City, 
      count(1) AS CountOrder 
FROM [dbo].['free-zipcode-database$']
Group by  City
Order BY Countorder Desc

现在我如何重用别名CountOrder来排名前5位然后拥有字符串09

1 个答案:

答案 0 :(得分:0)

你可以做这样的事情

SELECT TOP 5
        City,
        -- Count of all zipcodes
        COUNT(*) CountOrder,
        -- Only count zipcodes that contain 09
        COUNT(CASE WHEN ZipCode LIKE '%09%' THEN 1 END) Zip09Count
FROM    [dbo].['free-zipcode-database$']
GROUP BY City
ORDER BY CountOrder DESC