SQL查询在ALIAS列上使用WHERE

时间:2011-03-18 19:56:28

标签: sql-server-2008

这应该很简单,但我收到“无效的列名称”错误。

SELECT Transaction, COUNT(ItemId) AS ItemCount
FROM TransactionTable
WHERE ItemCount > 5
GROUP BY Transaction
ORDER BY ItemCount DESC

这个语句在没有WHERE子句的情况下工作,因为ORDER BY正在使用列别名,所以这对我来说似乎是双重标准。

4 个答案:

答案 0 :(得分:6)

使用HAVING并再次指定计数

SELECT Transaction, COUNT(ItemId) AS ItemCount
FROM TransactionTable
GROUP BY Transaction
HAVING COUNT(ItemId) > 5
ORDER BY ItemCount DESC

ORDER BY使用别名的原因是因为SQL查询按此顺序处理

FROM(incl join)
ON
OUTER
WHERE
GROUP BY HAVING
SELECT
订购单 TOP

答案 1 :(得分:0)

SELECT [Transaction], COUNT(ItemId) AS ItemCount
FROM TransactionTable
WHERE ItemCount > 5
GROUP BY COUNT(ItemId) 
ORDER BY COUNT(ItemId) DESC

答案 2 :(得分:0)

您可以在ORDER BY中引用列别名(逻辑上)在SELECT之后处理。要在WHEREHAVING子句中使用列别名,您可以在表格表达式中定义SELECT,例如如下。

;WITH cte
     AS (SELECT Transaction ,
                COUNT(itemid) AS itemcount
         FROM   transactiontable
         GROUP  BY Transaction )
SELECT Transaction ,
       itemcount
FROM   transactiontable
WHERE  itemcount > 5
ORDER  BY itemcount DESC  

答案 3 :(得分:0)

WITH tempTable AS
(
  SELECT Transaction, COUNT(ItemId) AS ItemCount
  FROM TransactionTable
)
SELECT * 
FROM tempTable
WHERE ItemCount > 5
GROUP BY Transaction
ORDER BY ItemCount DESC