Way to find rows with a same ID and only keep one row
I have a working query that will return some results(records) from my database, like:
123|John Williams|IL|M|06/01/2011|ACTIVE
124|Mary Haque|NY|F|TERMINATED|06/30/2011
124|Mary Haque|NY|F|07/01/2011|ACTIVE
125|Alex Chan|VA|07/01/2011|ACTIVE
126|Rob Kreb|VA|TERMINATED|06/20/2011
As you can see, the result is simply a list of customer records, while the last two fields indicate whether the member is active or terminated and associated active/terminated date.
The complication now is, as you can see for member with ID 124 (Mary Haque), she has two records, and for this kind of two-record customer, I only want to keep the row where the member is active while totally ignore her terminated history. So for example, the desired output for the above should be:
123|John Williams|IL|M|06/01/2011|ACTIVE
124|Mary Haque|NY|F|07/01/2011|ACTIVE
125|Alex Chan|VA|07/01/2011|ACTIVE
126|Rob Kreb|VA|TERMINATED|06/20/2011
as you can see, now Mary Haque only has her active information on the result. The above result is generate by a SQL "Select" query, but I couldn't simply append a "WHERE status=ACTIVE" to this query because I still want to keep the members that only has ONE record like Rob Kreb above even though he is terminated. I only want the filtering for TERMINATED member record to take place when a certain member has two records.
FYI, my current query looks like this:
SELECT * FROM customer_change WHERE CUSTOMER_LOGIN NOT IN(SELECT CUSTOMER_LOGIN FROM customer_full WHERE 开发者_Go百科CUSTOMER_LOGIN IS NOT NULL)
UNION
SELECT * FROM customer_change WHERE CUSTOMER_POINTS=0 AND CUSTOMER_LOGIN NOT IN(SELECT CUSTOMER_LOGIN FROM customer_full WHERE CUSTOMER_POINTS=0 AND CUSTOMER_LOGIN IS NOT NULL)
Thanks for the help in advance!
colX
and colY
are the last 2 columns of the query:
SELECT *
FROM (your_UNION_query) AS p
WHERE NOT ( colX = 'TERMINATED'
AND EXISTS
( SELECT *
FROM (your_UNION_query) AS q
WHERE q.id = p.id
AND q.colY = 'ACTIVE'
)
)
Something like this will do the trick:
DELETE
FROM tablename
WHERE tablename.status = 'TERMINATED'
AND tablename.id IN(SELECT
id
FROM (SELECT
t.id
FROM tablename t
GROUP BY t.id
HAVING COUNT(t.id) > 1) AS T1)
Assuming that id is the field refering to 124,125, etc.
精彩评论