Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get minimum value between two columns for each row

This is my data table:

| uid |   date   | visit | transactionDate |
+-----+----------+-------+-----------------+
|  1  | 6/2/2014 |   1   |     6/9/2014    |
|  1  | 6/2/2014 |   1   |     8/4/2014    |
|  2  | 6/2/2014 |   1   |     8/2/2014    |
|  2  | 6/2/2014 |   1   |     10/17/2014  |
|  2  | 6/2/2014 |   1   |     10/20/2014  |
|  3  | 6/2/2014 |   1   |     6/9/2014    |
|  3  | 6/2/2014 |   1   |     6/10/2014   |
|  3  | 6/2/2014 |   1   |     6/11/2014   | 
|  3  | 6/2/2014 |   1   |     6/12/2014   |
|  3  | 6/2/2014 |   1   |     6/14/2014   |
|  3  | 6/2/2014 |   1   |     6/15/2014   |
|  3  | 6/2/2014 |   1   |     6/17/2014   |
|  3  | 6/2/2014 |   1   |     6/18/2014   |
|  3  | 6/2/2014 |   1   |     6/23/2014   |

I am trying to write a query to pull the minimum of the two columns date and transaction date. Is there a way to do something like MIN(date, transactionDate)? The query should select something like this:

uid 1 then minimum of date and transaction_dt
uid 2 then min date and transaction_dt
like image 303
sai Avatar asked Dec 09 '14 05:12

sai


2 Answers

Use CASE condition.

SELECT uid, visit, 
   CASE WHEN date < transactionDate THEN date ELSE transactionDate END AS minDate
FROM table;
like image 166
Saravana Kumar Avatar answered Oct 11 '22 22:10

Saravana Kumar


Use LEAST() function with MIN() function.

Try this:

SELECT a.uid, MIN(LEAST(a.date, a.transaction_dt)) tdate 
FROM tableA a 
GROUP BY a.uid;

OR

SELECT a.uid, MIN(a.tdate) tdate
FROM (SELECT a.uid, MIN(a.date) tdate FROM tableA a GROUP BY a.uid
      UNION 
      SELECT a.uid, MIN(a.transaction_dt) tdate FROM tableA a GROUP BY a.uid
     ) AS a
GROUP BY a.uid;
like image 39
Saharsh Shah Avatar answered Oct 11 '22 21:10

Saharsh Shah