0

This is my current result from MySQL table tbl_msresponse

MobileNo         Time                     Status
xxxxx69333       2019-09-15 13:11:54      FAILED 
xxxxx69333       2019-09-15 14:12:16      FAILED
xxxxx69333       2019-09-15 14:21:34      DELIVERED **<- this row required**
xxxxx88779       2019-09-15 13:11:54      FAILED **<- this row required**
xxxxx76555       2019-09-15 14:12:16      FAILED
xxxxx76555       2019-09-15 14:21:34      DELIVERED **<- this row required**

From the above I want

 MobileNo        Time                     Status
 xxxxx69333      2019-09-15 14:21:34      DELIVERED 
 xxxxx88779      2019-09-15 13:11:54      FAILED 
 xxxxx76555      2019-09-15 14:21:34      DELIVERED 

So, now I want only DELIVERED row. If there is no DELIVERED row, I want show only last FAILED row of MobileNo based on Time col. How can I achieve this in MySQL?

Madhur Bhaiya
  • 28,155
  • 10
  • 49
  • 57
Learner
  • 46
  • 4

3 Answers3

0

You can use limit for take just 1 result, if you want to last you need to use DESC keyword otherwise ASC you can write like this:

Select * from table_name where Status="Delivered" or Status = Select status from table_name where Status="Failed" order by Time DESC LIMIT 1;
Mert Akkanat
  • 111
  • 7
0

If you with to use stored procedure, then here is my solution using stored procedure. Actually you can write if/else condition inside stored procedure. The condition basically check if any row exists with DELIVERED status then return all rows else return FAILED status row order by Time and limit is 1.

Here is procedure:

DELIMITER //
create procedure my_procedure()
begin
    IF NOT EXISTS (SELECT * FROM my_response where status='DELIVERED')
    THEN
        SELECT * from tbl_msresponse WHERE Status='FAILED' order by Time DESC LIMIT 1;
    ELSE
        SELECT * from tbl_msresponse WHERE Status='DELIVERED';
    END IF;
end //
DELIMITER;

And you can call this procedure like:

call my_procedure();
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Sudhir Ojha
  • 3,247
  • 3
  • 14
  • 24
0

Assuming status is binary (ie failed or delivered) then discussion of status is irrelevant, all you need is the most recent entry by mobileno

select t.*
from t 
where time = (select max(time) from t t1 where t1.mobileno = t.mobileno);

+----------+---------------------+-----------+
| MobileNo | Time                | Status    |
+----------+---------------------+-----------+
|    69333 | 2019-09-15 14:21:34 | DELIVERED |
|    88779 | 2019-09-15 13:11:54 | FAILED    |
|    76555 | 2019-09-15 14:21:34 | DELIVERED |
+----------+---------------------+-----------+
3 rows in set (0.00 sec)
P.Salmon
  • 17,104
  • 2
  • 12
  • 19