我找不到一個函數來支持我正在嘗試的方法。SQL Row_Number()(分區由...排序依據...)IGNORES命令語句
讓我們假設我們有如下表,包含一個字段排序順序和一定的重複
+----------+----------+-----+-------------+-----------+ | UniqueId | Id | Qty | RetailPrice | SortOrder | +----------+----------+-----+-------------+-----------+ | 3124 | 92361725 | 25 | 269.99 | 1 | | 2627 | 92361725 | 25 | 269.99 | 2 | | 7635 | 92361725 | 25 | 269.99 | 3 | | 8732 | 92361725 | 25 | 269.99 | 4 | | 3791 | 92361725 | 20 | 269.99 | 5 | | 4328 | 92361725 | 25 | 269.99 | 6 | +----------+----------+-----+-------------+-----------+
我要列舉我行增加其價值,當副本被發現,如果沒有則重置行號。結果必須在列中顯示RN下表,如果數量是評價柱:
+----------+----------+-----+-------------+-----------+----+ | UniqueId | Id | Qty | RetailPrice | SortOrder | rn | +----------+----------+-----+-------------+-----------+----+ | 3124 | 92361725 | 25 | 269.99 | 1 | 1 | | 2627 | 92361725 | 25 | 269.99 | 2 | 2 | | 7635 | 92361725 | 25 | 269.99 | 3 | 3 | | 8732 | 92361725 | 25 | 269.99 | 4 | 4 | | 3791 | 92361725 | 20 | 269.99 | 5 | 1 | | 4328 | 92361725 | 25 | 269.99 | 6 | 1 | +----------+----------+-----+-------------+-----------+----+
我試圖用ROW_NUMBER()函數,但我不能讓我的結果想
;WITH Table1 AS(
SELECT 3124 UniqueId,92361725 Id, 25 Qty, 269.99 RetailPrice, 1 SortOrder UNION ALL
SELECT 2627 UniqueId,92361725 Id, 25 Qty, 269.99 RetailPrice, 2 SortOrder UNION ALL
SELECT 7635 UniqueId,92361725 Id, 25 Qty, 269.99 RetailPrice, 3 SortOrder UNION ALL
SELECT 8732 UniqueId,92361725 Id, 25 Qty, 269.99 RetailPrice, 4 SortOrder UNION ALL
SELECT 3791 UniqueId,92361725 Id, 20 Qty, 269.99 RetailPrice, 5 SortOrder UNION ALL
SELECT 4328 UniqueId,92361725 Id, 25 Qty, 269.99 RetailPrice, 6 SortOrder
)
SELECT UniqueId, Id, Qty, RetailPrice, SortOrder,
ROW_NUMBER() OVER (PARTITION BY Qty ORDER BY SortOrder) rn
FROM Table1
+----------+----------+-----+-------------+-----------+----+ | UniqueId | Id | Qty | RetailPrice | SortOrder | rn | +----------+----------+-----+-------------+-----------+----+ | 3791 | 92361725 | 20 | 269.99 | 5 | 1 | | 3124 | 92361725 | 25 | 269.99 | 1 | 1 | | 2627 | 92361725 | 25 | 269.99 | 2 | 2 | | 7635 | 92361725 | 25 | 269.99 | 3 | 3 | | 8732 | 92361725 | 25 | 269.99 | 4 | 4 | | 4328 | 92361725 | 25 | 269.99 | 6 | 5 | +----------+----------+-----+-------------+-----------+----+
在ORDER BY完全被忽略,任何人都可以幫忙嗎?
ORDER BY不會被忽略。如果按Qty進行分區,則將第6行與第1-4行分組。你需要嘗試一個「差距和離島」的方法。看看LAG功能。 –
它根本沒有被忽略。盯緊了。您正在根據「數量」列對結果進行分區。因此,在第一個分區中,「rn」是1.在下一個分區中,「rn」基於「Qty」。你還想要什麼? – ViKiNG
謝謝Tab Alleman,但不幸的是,這必須在2008 R2數據庫引擎中接近,因爲我在標籤中指定了 –