如何用mysql排除记录?

时间:2016-07-14 08:54:04

标签: mysql sql

我有一个循环查看事件表的查询。如果第一次测试通过,我们只对当天进行的第一次测试感兴趣。所以,例如,如果我们有:

Me.Dispose()

那么我们想要的只是那些通过的第一次测试。如果DX125在半小时后继续通过,那么我们不希望在数据集中使用DX125。

所以上面的表格会返回:

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

我尝试过使用:

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

将失败的测试作为空值返回,我相反他们根本就没有。通过设置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; 语句可以优雅地实现这一点,如果为false则不返回任何内容。可以吗?

感谢。

2 个答案:

答案 0 :(得分:2)

您可以使用Having()子句在分组后排除行:

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

修改:根据第一条评论更新了答案。包含Having()条款

答案 1 :(得分:1)

此查询将为那些没有任何失败的组提供序列号,测试名称和最早的测试时间。 HAVING子句过滤掉有一个或多个失败的组。

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