简体   繁体   中英

How do I exclude records with mysql if?

I have a query that loops through a table of events. We're only interested in the first tests taken that day if that first test passed. So, for example, if we have:

s/n     test_result first test taken and passed
DX123   Terminated  2016-06-16 09:33:38
DX124   Passed      2016-06-16 10:12:01
DX125   Failed      2016-06-16 08:27:48
DX126   Passed      2016-06-16 08:28:16
DX127   Passed      2016-06-16 08:25:02

Then what we want is only those first tests that passed. If DX125 went on to pass half an hour later then we don't want DX125 in the dataset.

So the table above would return:

s/n     test_result first test taken and passed
DX124   Passed      2016-06-16 10:12:01
DX126   Passed      2016-06-16 08:28:16
DX127   Passed      2016-06-16 08:25:02

I've tried using:

select serial_number, test_name, 
    IF(test_result = 'passed', min(START_DATE_TIME), null) as 'first test taken and passed' 

from 
    test_results 
 where
     (test_time > '2016-06-16 00:00:00' AND test_time < '2016-06-16 23:59:59')

group by serial_number, test_name 
order by serial_number asc;

That returns the failed tests as nulls, I'd rather they weren't there at all. This would be achieved elegantly by setting the if statement to return nothing if false. Can it be done?

Thanks.

You can use the Having() clause to exclude rows after grouping:

SELECT serial_number,
       test_name,
       IF(status = "Passed",CONVERT(MIN(test_time), CHAR),'not passed') AS 'first_test_taken_and_passed'
FROM 
    test_results 
WHERE
    test_time > '2016-06-16 00:00:00'
    AND test_time <= '2016-06-16 23:59:59'
GROUP BY serial_number, test_name 
HAVING first_test_taken_and_passed <> "not passed"
ORDER BY serial_number ASC

Edit : Updated answer according to first comment. Included Having() clause

This query will give the serial number, test name, and earliest time of test taking, for those groups which do not have any failures in them. The HAVING clause filters away groups which had one or more failures.

SELECT serial_number,
       test_name,
       MIN(test_time) AS 'first test taken and passed'
FROM 
    test_results 
WHERE
    test_time > '2016-06-16 00:00:00' AND test_time < '2016-06-16 23:59:59'
GROUP BY serial_number, test_name 
HAVING SUM(CASE WHEN test_result != 'passed' THEN 1 ELSE 0 END) = 0
ORDER BY serial_number ASC

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM