窗函數在ANSI規範定義的GROUP BY
,HAVING
,WHERE
的處理邏輯後執行。
更具體地說,它們在Logical Query Processing flow chart here的步驟5.1和6中被允許。
我想他們可以這樣來定義它的另一種方式,並允許GROUP BY
,WHERE
,HAVING
使用窗口函數與窗口是合乎邏輯的結果設定在該階段的開始,但假設他們有和我們被允許建立這樣的查詢作爲
SELECT a,
b,
NTILE(2) OVER (PARTITION BY a ORDER BY b) AS NtileForSelect
FROM YourTable
WHERE NTILE(2) OVER (PARTITION BY a ORDER BY b) > 1
GROUP BY a,
b,
NTILE(2) OVER (PARTITION BY a ORDER BY b)
HAVING NTILE(2) OVER (PARTITION BY a ORDER BY b) = 1
有四個不同的邏輯窗口在播放好運運算出這將是什麼結果!另外,如果在HAVING
中您實際上想要從上面的GROUP BY
級別的表達式篩選,而不是以GROUP BY
之後的結果行作爲窗口?
CTE版本更詳細,但也更明確,更易於遵循。
WITH T1 AS
(
SELECT a,
b,
NTILE(2) OVER (PARTITION BY a ORDER BY b) AS NtileForWhere
FROM YourTable
), T2 AS
(
SELECT a,
b,
NTILE(2) OVER (PARTITION BY a ORDER BY b) AS NtileForGroupBy
FROM T1
WHERE NtileForWhere > 1
), T3 AS
(
SELECT a,
b,
NtileForGroupBy,
NTILE(2) OVER (PARTITION BY a ORDER BY b) AS NtileForHaving
FROM T2
GROUP BY a,b, NtileForGroupBy
)
SELECT a,
b,
NTILE(2) OVER (PARTITION BY a ORDER BY b) AS NtileForSelect
FROM T3
WHERE NtileForHaving = 1
由於這些在SELECT
語句都被定義和被混疊是容易實現的消除歧義從不同級別例如結果只需通過切換WHERE NtileForHaving = 1
到NtileForGroupBy = 1
通過'row_number()'分組有什麼意義?每個項目將獨立成組。不過,這個問題很合理。 – dasblinkenlight
事情是考慮如果我有重複的發票,在這種情況下,我想保持這一點。你可以想一想爲什麼我應該分組。事情是我想爲什麼它是這樣的?爲什麼我們不能在組中使用窗口函數? – Mari
它將如何產生歧義。你可以解釋嗎?如果我只想在where子句中選擇排名值2。如果它會造成模糊性 – Mari