Sql-Server-2012
如何在查詢中顯示執行記錄數
我正在研究 SQL SERVER 2012,我一直在試圖弄清楚如何在 group by 語句中包含執行記錄數。例如,查詢看起來像:
SELECT CUSTOMER_ID, TRANSACTION_ID, COUNT FROM TRANSACTIONS GROUP BY CUSTOMER_ID, TRANSACTION_ID ORDER BY CUSTOMER_ID, TRANSACTION_ID
輸出看起來像:
10 100 1
10 108 2
10 125 3
10 140 4
12 102 1
12 103 2
12 138 3
15 135 1
我感謝有關如何查詢此資訊的任何建議。
你會想要使用一個視窗函式,比如
ROW_NUMBER()
這個:SELECT CUSTOMER_ID, TRANSACTION_ID, ROW_NUMBER() OVER (PARTITION BY CUSTOMER_ID ORDER BY TRANSACTION_ID) AS [Count] -- Running incremental count of rows / TRANSACTION_ID per CUSTOMER_ID FROM TRANSACTIONS GROUP BY CUSTOMER_ID, TRANSACTION_ID ORDER BY CUSTOMER_ID, TRANSACTION_ID