For a mysql database
I have a table which includes duplicate rows because of date values in several columns. I am looking to select a single row for each unique customer id based on a max date value evaluated across several date columns
[customer id, startDate, StopDate, modifyDate, buyDate]
For each customer id, i'd like to return the row that has the maximum date either in the startDate, StopDate, modifyDate or buyDate columns ( there are some nulls in the date columns.
editing to include example - but to sure how to create a table here:
*** Edit
Been trying for quite awhile now to create a table here with an example. can't figure out. So posting an image? the desired rows to the returned indicated in red.
答案 0 :(得分:0)
Assuming that the values are never NULL
, you can use greatest()
:
select t.*
from table t
where greatest(t.startDate, stopDate, buyDate) =
(select max(greatest(t.startDate, stopDate, buyDate))
from t t2
where t2.customerid = t.customerid
);
Note: this will return multiple rows for a customer if more than one row contains the maximum date.