-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdeduplication.sql
More file actions
45 lines (40 loc) · 957 Bytes
/
deduplication.sql
File metadata and controls
45 lines (40 loc) · 957 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/*
Purpose:
Identify and remove duplicate records using window functions.
*/
-- Identify duplicate orders (same customer, same date, same amount)
SELECT
customer_id,
order_date,
order_amount,
COUNT(*) AS duplicate_count
FROM orders
GROUP BY customer_id, order_date, order_amount
HAVING COUNT(*) > 1;
-- Flag duplicates using ROW_NUMBER
SELECT *
FROM (
SELECT
*,
ROW_NUMBER() OVER (
PARTITION BY customer_id, order_date, order_amount
ORDER BY order_id
) AS rn
FROM orders
) sub
WHERE rn > 1;
-- Delete duplicates (example pattern)
-- DELETE FROM orders
-- WHERE order_id IN (
-- SELECT order_id
-- FROM (
-- SELECT
-- order_id,
-- ROW_NUMBER() OVER (
-- PARTITION BY customer_id, order_date, order_amount
-- ORDER BY order_id
-- ) AS rn
-- FROM orders
-- ) t
-- WHERE rn > 1
-- );