In the given inventory
table below:
SKU | COST | DATE YYMMDD |
---|---|---|
202114000 | 0 | 210109 |
202114000 | 12 | 210228 |
202115000 | 50 | 210108 |
202115000 | 30 | 210109 |
202116000 | 54 | 210103 |
202116000 | 60 | 210301 |
202116000 | 100 | 210605 |
I want to retain SKU with the latest date and remove all others, and just retaining one SKU per row.
My query script goes:
SELECT *
FROM `inventory`
WHERE
INUMBR IN (
SELECT
SKU
FROM
`inventory`
WHERE
SKU IN (
SELECT
SKU
FROM
`inventory`
GROUP BY
SKU
HAVING
COUNT(*) > 1
ORDER BY
SKU
)
GROUP BY
SKU
ORDER BY
SKU
)
AND
DATE IN (
SELECT
MIN (DATE) as DATE
FROM
`inventory`
WHERE
SKU IN (
SELECT
SKU
FROM
`inventory`
GROUP BY
SKU
HAVING
COUNT(*) > 1
ORDER BY
SKU
)
GROUP BY
SKU
ORDER BY
SKU
)
ORDER BY
SKU
However, this script is problematic. Why? because it will delete the two rows with the SKU
20211500
because, on the second IN
criteria in the WHERE
clause, two of DATE
s will match: 210109
and 210108
. How can I improve my query?
NOTE: The table is just an example, I will be dealing with millions of rows here.