这应该很简单,但我收到“无效的列名称”错误。
SELECT Transaction, COUNT(ItemId) AS ItemCount
FROM TransactionTable
WHERE ItemCount > 5
GROUP BY Transaction
ORDER BY ItemCount DESC
这个语句在没有WHERE子句的情况下工作,因为ORDER BY正在使用列别名,所以这对我来说似乎是双重标准。
答案 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
之后处理。要在WHERE
或HAVING
子句中使用列别名,您可以在表格表达式中定义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