你不能使用列別名GROUP BY
條款。請參閱Conceptual Order of Evaluation of a Select Statement,您將看到以下順序評估(邏輯)子句:FROM, WHERE, GROUP BY, HAVING, SELECT, DISTINCT, UNION, ORDER BY
。
即發動機不完全是如何執行的操作,但它是你爲什麼不能GROUP BY
子句中使用的東西從SELECT
語句紮實的實踐認識一個有用的啓發 - 這在邏輯上不是可用到GROUP BY
條款,因爲它在稍後評估。
有幾種方法可以解決此問題:
重複GROUP BY
子句中的整個表達式:
SELECT
City =
CASE location_id when 1 then 'DELHI' when 2 then 'AHMEDABAD'
when 4 then 'HYDERABAD' when 5 then 'KOLKATA' when 6 then 'BANGALORE'
when 7 then 'MUMBAI' when 8 then 'CHENNAI'
END,
Total = Count(*)
FROM #tmptab1
GROUP BY
CASE location_id when 1 then 'DELHI' when 2 then 'AHMEDABAD'
when 4 then 'HYDERABAD' when 5 then 'KOLKATA' when 6 then 'BANGALORE'
when 7 then 'MUMBAI' when 8 then 'CHENNAI'
END
使用派生表:
SELECT
City,
Total = Count(*)
FROM
(
SELECT
City =
CASE location_id when 1 then 'DELHI' when 2 then 'AHMEDABAD'
when 4 then 'HYDERABAD' when 5 then 'KOLKATA' when 6 then 'BANGALORE'
when 7 then 'MUMBAI' when 8 then 'CHENNAI'
END
FROM #tmptab1
) Cities
GROUP BY City;
使用公用表表達式(CTE),SQL Server 2005及更高版本:
WITH Cities AS (
SELECT
City =
CASE location_id
when 1 then 'DELHI'
when 2 then 'AHMEDABAD'
when 4 then 'HYDERABAD'
when 5 then 'KOLKATA'
when 6 then 'BANGALORE'
when 7 then 'MUMBAI'
when 8 then 'CHENNAI'
END
FROM #tmptab1
)
SELECT
City,
Total = Count(*)
FROM Cities
GROUP BY City;
使用CROSS應用,SQL Server 2005和了起來:
SELECT
City,
Total = Count(*)
FROM
#tmptab1
CROSS APPLY (
SELECT
City =
CASE location_id when 1 then 'DELHI' when 2 then 'AHMEDABAD'
when 4 then 'HYDERABAD' when 5 then 'KOLKATA' when 6 then 'BANGALORE'
when 7 then 'MUMBAI' when 8 then 'CHENNAI'
END
) C
GROUP BY City;
因爲你的表情是確定性的,這是可能的,你可以簡單地做GROUP BY location_id
,然而,這是不正常的的情況下,你不應該期望能夠通過選擇單個列來繞過正常的聚合分組邏輯,因爲大多數情況下這種CASE表達式增加了非確定性的值。事實上,因爲信息不僅是確定性的,而是關於真實世界(而不是業務規則),我建議您不要在查詢中編碼這些信息!創建一個Location
表並加入到它。將可更改的用戶數據直接放入查詢並不是最佳做法 - 查詢應該記錄過程,而不是內容,以及如果添加新的location_id,該怎麼辦?所有使用它的查詢都必須更改。此外,如果多個location_id
可以指向同一個城市,則location_id
的分組將無法正常工作。
謝謝你的詳細解釋,真的很感激.. –