将 SQL count(*) 与别名列一起使用

Use SQL count(*) with an alias column

您好,我正在尝试使用 https://data.stackexchange.com/Whosebug/query/new 从我的国家获得堆栈溢出金牌得主。这是我的查询,

SELECT TOP 1000
  ROW_NUMBER() OVER(ORDER BY Gold badges DESC) AS [#], 
  UserId AS [User Link], 
  COUNT(*) AS "Gold badges"
FROM Badges, Users
WHERE Name IN ('Copy Editor', 'Electorate', 'Famous Question', 'Fanatic', 'Great Answer', 'Great Question', 'Legendary', 'Marshal', 'Populist', 'Publicist', 'Reversal', 'Stellar Question', 'Steward', 'Unsung Hero')
AND LOWER(Location) LIKE '%sri lanka%' AND Users.Id = Badges.UserId
GROUP BY UserId
ORDER BY COUNT(*) DESC

我需要做的是让我所有国家的金牌获得者获得金牌数量名称和行号。但是我收到了这个错误,

Incorrect syntax near the keyword 'DESC'.

如果有人能提供帮助就太好了。

我想你想要这样的东西:

SELECT TOP 1000
       ROW_NUMBER() OVER (ORDER BY COUNT(*) DESC) AS [#], 
       u.id AS User_Link, 
       COUNT(*) AS Gold_badges
FROM Badges b JOIN
     Users u
     ON u.Id = b.UserId
WHERE ?.Name IN ('Copy Editor', 'Electorate', 'Famous Question', 'Fanatic', 'Great Answer', 'Great Question', 'Legendary', 'Marshal', 'Populist', 'Publicist', 'Reversal', 'Stellar Question', 'Steward', 'Unsung Hero'
                ) AND
     LOWER(?.Location) LIKE '%sri lanka%' AND 
GROUP BY u.id
ORDER BY COUNT(*) DESC;

备注:

  • ? 用于标识列来源的 table 别名。
  • 从不FROM 子句中使用逗号。
  • 这修复了连接语法以使用正确的、显式的、标准连接。
  • 您不能在同一个 SELECT 中的其他任何地方使用 table 别名。所以,重复这个表达式。