I have a table that has duplicated cardnbr
's. I need to pull out demographics that are the most recently used by the customer. I have a date field (lastvisit)
that shows their most recently used card. Here's an example query that doesn't work:
SELECT cardnbr, fname, lname, address, city, state, postal
FROM cards
WHERE lastvisit = MAX( lastvisit )
GROUP BY cardnbr
How can I format my query to do this but actually work?
Also, the primary key for this table was created after duplicated data was added to the table.
Best Answer
Assuming you have a
PRIMARY KEY
or otherwiseUNIQUE KEY
calledid
(replace with whatever it's called in your table), consider the following query:The idea is to get, per
cardnbr
, theid
where thelastvisit
is most recent. Then, get all row data for thoseid
s.The above is a simplification of Selecting Top N Records Per Group, where
N = 1
.Another way to solve it is described in Selecting Non Aggregated Column Data in GROUP BY. The query presented in this post actually provides better performance than the above, but uses some parsing and casting to get the final results (all columns parsed as strings, then cast back to their original types). Also see this post. Apologies for the many links, but each post presents with a different solution to the problem.