I have a table that looks like the below in SQL
I would like to select the row with the earliest date in either the PR create date or AC create date field. So in this case, I would want these two records.
I know that I can write
Select email, min(PR_create_date) from table
group by email
However, this will only find the minimum date in the PR_create_date column. How can I find the minimum date in either the PR_create_date or AC_create_date columns?
You can use
SELECT email,
MIN(least(pr_create_date, ac_create_date))
FROM my_table
GROUP BY email
Function least
returns the minimal value of its arguments.
But if one of arguments is NULL
then the result is NULL
too. So you are to write some logic to handle nulls, depending on how nulls must be treated in your business logic: for example you can use "special date" in the far past or future to replace nulls as
SELECT email,
MIN( least( ifnull(pr_create_date, DATE '2999-12-31'),
ifnull(ac_create_date, DATE '2999-12-31')) )
FROM my_table
GROUP BY email
But in the simplest case when dates are excluding (ie in every row exactly one of the dates is null) its enough to just write
SELECT email,
MIN( ifnull(pr_create_date, ac_create_date) )
FROM my_table
GROUP BY email
One more solution :
select temp.EMAIL, min(temp.PR_AC_CREATE_DATE)
from
(
select EMAIL , min(PR_CREATE_DATE) as PR_AC_CREATE_DATE
from table
group by email
union
select EMAIL, min(AC_CREATE_DATE)
from table
group by email
) temp
group by temp.EMAIL ;
Use COALESCE function, solution is for generic sql may be run on mysql
select email,min(COALESCE(PR_create_date,AC_create_date)) as mindt
from tab
group by email
You can try a more robust solution like:
SELECT * FROM (SELECT * FROM my_table ORDER BY pr_create_date DESC,ac_create_date DESC LIMIT 5);
Order by: specify columns and ordering rule (ascending ASC(default) / descending DESC)
Limit: number of records you want. This will give the top 5 latest records. Try it.
Select email,
Case When PR_create_date < AC_create_date Then PR_create_date
When AC_create_date < PR_create_date Then AC_create_date
End As TheMin
From YourTableNameHere
Group By email
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.