這應該很容易,但我得到一個「無效列名稱」錯誤。SQL查詢使用列ALIAS
SELECT Transaction, COUNT(ItemId) AS ItemCount
FROM TransactionTable
WHERE ItemCount > 5
GROUP BY Transaction
ORDER BY ItemCount DESC
這種說法作品,未經這似乎是雙重標準,對我來說,因爲ORDER BY使用列別名WHERE子句。
這應該很容易,但我得到一個「無效列名稱」錯誤。SQL查詢使用列ALIAS
SELECT Transaction, COUNT(ItemId) AS ItemCount
FROM TransactionTable
WHERE ItemCount > 5
GROUP BY Transaction
ORDER BY ItemCount DESC
這種說法作品,未經這似乎是雙重標準,對我來說,因爲ORDER BY使用列別名WHERE子句。
使用HAVING
,並指定統計再次
SELECT Transaction, COUNT(ItemId) AS ItemCount
FROM TransactionTable
GROUP BY Transaction
HAVING COUNT(ItemId) > 5
ORDER BY ItemCount DESC
原因ORDER BY
正在與別名是因爲SQL查詢順序
處理FROM(包括聯接)
ON
OUTER
其中
GROUP BY
HAVING
SELECT
ORDER BY
TOP
SELECT [Transaction], COUNT(ItemId) AS ItemCount
FROM TransactionTable
WHERE ItemCount > 5
GROUP BY COUNT(ItemId)
ORDER BY COUNT(ItemId) DESC
您可以參考列別名在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
WITH tempTable AS
(
SELECT Transaction, COUNT(ItemId) AS ItemCount
FROM TransactionTable
)
SELECT *
FROM tempTable
WHERE ItemCount > 5
GROUP BY Transaction
ORDER BY ItemCount DESC
感謝,正是我需要的 – Spidy 2011-03-18 20:00:05