Sql-Server
查找具有重複值的行
Account
我在表格和表格之間有一對多的關係ScheduledPayment
。一個帳戶可以進行多次付款,但每天最多只能進行**一次付款。**雖然不太可能,但我需要滿足兩種情況……
- 如果一天有一個或多個
Payment
記錄AccountId
,具有不同的付款和/或參考,則所有付款都應標記為已取消。- 如果一天有多個
Payment
記錄AccountId
,且付款和參考相同,則一條記錄應為獲勝者,另一條記錄為已取消。實際上,我預計不會看到這種情況,因為如果兩個使用者同時處理相同的記錄,則它歸結為程式碼中的並發問題。
任何想法將不勝感激!
帳戶 --------- 帳戶ID --------- 1 2 3 4
預定付款 ---------------- ScheduledPaymentId | 帳戶 ID | 金額 | 參考 | 狀態 ------------------------------------------------------------ 1 | 1 | 100 | ABCDE | 居住 2 | 1 | 100 | ABCDE | 直播(對於這兩個,1 個獲勝者和兩個標記為取消) 3 | 2 | 100 | ABCDE | 居住 4 | 2 | 110 | ABCDE | 居住 5 | 2 | 110 | ABCDE | 居住 6 | 2 | 130 | ABCDE | 直播(對於這些,所有都將被標記為已取消) 7 | 3 | 100 | ABCDE | 居住 8 | 4 | 100 | ABCDE | 居住
這應該返回標記需要注意的記錄。我將標記放在 SELECT 中,但您可以輕鬆地將其轉換為第二個 CTE,然後簡單地選擇要清理的付款。
-- -- find all accounts with more than one payment and mark payments to cancel -- WITH cte_DuplicatePayments AS ( SELECT COUNT(*) OVER(PARTITION BY accountID) AS numberOfPaymentsPerAccountID , COUNT(*) OVER(partition BY accountID, amount) AS numberOfPaymentsPerAccountIDAndAmount , ROW_NUMBER() OVER(partition BY accountID ORDER BY amount asc) AS PaymentsNumberPerAccountID , * FROM ScheduledPayment ) SELECT CASE WHEN numberOfPaymentsPerAccountID != numberOfPaymentsPerAccountIDAndAmount THEN 'MARK AS CANCELLED: Duplicate Payments with amount mismatch' WHEN PaymentsNumberPerAccountID > 1 THEN 'MARK AS CANCELLED: Duplicate Payments with matching amount' ELSE '' END AS PaymentAuditAction , ScheduledPaymentID, accountID, amount, FROM cte_DuplicatePayments WHERE numberOfPaymentsPerAccountID > 1