I am working on a logic for merging duplicate rows from one table(1000+ rows) into another empty table based on the product_id and extraction_date. The extraction_date is used to determine which data is the latest. In cases where extraction_date is same in multiple rows my logic fails. Here's an example:
create or replace table source(v variant);
INSERT INTO source SELECT parse_json('{
"pd": {
"extraction_date": "1644471240",
"product_id": "357946",
"retailerName": "retailer",
"productName":"product"
}
}');
INSERT INTO source SELECT parse_json('{
"pd": {
"extraction_date": "1644471240",
"product_id": "357946",
"retailerName": "retailer2",
"productName":"product2"
}
}');
//Merge logic:
create or replace TABLE target AS
SELECT * from source
where v:pd:extraction_date not in
(SELECT c1.v:pd:extraction_date
FROM source c1, source c2 where
c1.v:pd:product_id=c2.v:pd:product_id and
c1.v:pd:extraction_date>c2.v:pd:extraction_date);
In the given example the target table will have two duplicate rows because of the same extraction_date. Please suggest me a modification which only selects one row when extraction_date is same.