Editing
Finding and deleting duplicates
(section)
Jump to navigation
Jump to search
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
====Finding and Deleting Duplicates==== To ensure only the most recent record for each primary key is retained, duplicates can be identified and removed using the following steps: 1. **Identify Duplicates**: Use the `ROW_NUMBER()` function to assign a rank to each row for the same primary key, ordered by `kptinsertedat` or `filesourcekey`. For example: <syntaxhighlight lang="sql" line> WITH ranked_rows AS ( SELECT "ACC45ID", filesourcekey, kptinsertedat, ROW_NUMBER() OVER (PARTITION BY "ACC45ID" ORDER BY kptinsertedat DESC) AS r FROM indici_staging.accidents ) SELECT * FROM ranked_rows WHERE r > 1; </syntaxhighlight> 2. **Delete Duplicates**: Once duplicates are identified, rows where <code>r > 1</code> can be deleted while retaining the most recent record: <syntaxhighlight lang="sql" line> WITH ranked_rows AS ( SELECT "ACC45ID", filesourcekey, ROW_NUMBER() OVER (PARTITION BY "ACC45ID" ORDER BY kptinsertedat DESC) AS r FROM indici_staging.accidents ) DELETE FROM indici_staging.accidents WHERE ( "ACC45ID", filesourcekey ) IN ( SELECT "ACC45ID", filesourcekey FROM ranked_rows WHERE r > 1 ); </syntaxhighlight> This ensures that only the most recent record for each primary key remains in the staging table, ready to be inserted into the target table.
Summary:
Please note that all contributions to Kautepedia are considered to be released under the Creative Commons Attribution-NonCommercial-ShareAlike (see
Kautepedia:Copyrights
for details). If you do not want your writing to be edited mercilessly and redistributed at will, then do not submit it here.
You are also promising us that you wrote this yourself, or copied it from a public domain or similar free resource.
Do not submit copyrighted work without permission!
Cancel
Editing help
(opens in new window)
Navigation menu
Personal tools
British English
Not logged in
Talk
Contributions
Log in
Namespaces
Page
Discussion
British English
Views
Read
Edit
Edit source
View history
More
Search
Navigation
Main page
Recent changes
Random page
Help about MediaWiki
Tools
What links here
Related changes
Special pages
Page information