Consider the following table.
CREATE TABLE my_table
(
cost decimal(10,2),
ref int
);
INSERT INTO my_table(cost, ref)
VALUES (0.00, 1),
(0.50, 1),
(-1.89, 1),
(0.00, 2),
(0.00, 2),
(0.00, 2),
(1.23, 3),
(-9.47, 3),
(111.23, 3),
(12.00, 3);
My aim with this table is to filter it to remove all rows where ref = 2
(rows 4, 5, and 6 in the above), because all of the cost values where ref = 2
are zero.
I've got halfway there by working out which values of ref
have AT LEAST one row where cost is not zero:
SELECT DISTINCT ref
INTO refs_to_keep
FROM my_table
WHERE cost != 0.00;
So what I'd like then like to do to finish the job is something like
DELETE FROM my_table
WHERE ref NOT IN "list of refs in the refs_to_keep table";
But I don't know the syntax for that. Can anyone help me out please?
Or maybe there's another way to achieve this without the intermediate refs_to_keep
stage?
Yeah you are pretty much there already although you don't need to create the temp table you can just use a sub-query:
You can see it working here: https://www.db-fiddle.com/f/fAYuenfopm4BkYFRNMKY9w/0