I have a table with the following columns: ClientID, Amount, etc. The problem is that some clients have two or more rows with Amount = 0
, and I want to remove these rows. I’ve searched some information but only found with unique identification.
Sample input:
ClientID | Amount |
---|---|
QER1 | 531 |
QER2 | 521 |
QER3 | 0 |
QER4 | 231 |
QER2 | 0 |
QER1 | 0 |
Expected Output:
ClientID | Amount |
---|---|
QER1 | 531 |
QER2 | 521 |
QER3 | 0 |
QER4 | 231 |
2
Answers
You could
INNER JOIN
on the same table to select the clients who have the sameCliendID
and then delete those who have anAmount
of0
The code you are looking for is this:
This will only remove rows if they have Amount = 0 and there is another amount with the same ClientId that is more than zero.
This second point may cause you issues, you can have ClientID with two rows of Amount = 0. If this is a problem you can Create a unique index which will clear this for you at the structural level:
Your problem is that if you have two identical rows (ClientID and Amount = 0) then there is no unqiue identifier to distinguish and only remove one of those rows, this is not something we can fix at the query level (ie by running queries on the data) but is a core structural problem with your database design. You should have a unique index id for each row, typically called a Primary Key.
Indexing your Amount column is recommended. Also adding a unique row identifier (Primary Key) is also highly recommended.
You can view this SQL in action here .