使用特定方案提取行

时间:2013-02-16 20:58:25

标签: sql oracle

我有一张包含以下详细信息的表格

EMP_NAME     TEST_RESULT   RUN_DATE
----------------------------------------------
John            Pass    12-FEB-2013 18:03:55
Albert          Fail    12-FEB-2013 18:24:29
Chris           Pass    12-FEB-2013 18:24:28
John            Fail    12-FEB-2013 19:32:35
Chris           Pass    12-FEB-2013 19:32:35
Steve           Pass    12-FEB-2013 20:04:35

现在我需要提取具有唯一名称和TEST_RESULT的行。但是,如果员工同时具有通过和失败结果,则测试结果应该只有“失败”结果。查询的结果应为

EMP_NAME     TEST_RESULT   RUN_DATE
----------------------------------------------
Albert          Fail    12-FEB-2013 18:24:29
Chris           Pass    12-FEB-2013 18:24:28
John            Fail    12-FEB-2013 19:32:35
Steve           Pass    12-FEB-2013 20:04:35

我所关心的只是一个员工姓名,如果该员工有两个结果通过和失败,请只显示FAIL记录,我不关心时间。如果员工有两个结果为“通过”和“通过”,我仍然需要一个记录,我不关心时间。

3 个答案:

答案 0 :(得分:2)


Select emp_name, test_result, run_date
from (
select emp_name, test_result, run_date,
row_number() over (partition by emp_name
order by test_result, run_date ) rn
from
T1)
where rn=1

答案 1 :(得分:1)

这样的事情可能有用。

select emp_name, test_result, run_date
from YourTable
where test_result = 'Fail'
union
select emp_name, test_result, run_date
from YourTable
where test_result = 'Pass'
and emp_name in 
(select emp_name
from YourTable
where TestResult = 'Pass'
minus
select emp_name
from YourTable 
where TestResult = 'Fail'
)

答案 2 :(得分:1)

SELECT EMP_NAME, TEST_RESULT, RUN_DATE
FROM (
  SELECT ROW_NUMBER() OVER (PARTITION BY t1.EMP_NAME ORDER BY RUN_DATE) AS RowNumber,
       t1.EMP_NAME, TEST_RESULT, RUN_DATE
  FROM MyTable t1
  LEFT JOIN 
  (SELECT DISTINCT EMP_NAME 
   FROM MyTable
   WHERE TEST_RESULT = 'Fail' 
  ) AS EMP_With_Failure ON t1.EMP_NAME = EMP_With_Failure.EMP_Name
  WHERE t1.TEST_RESULT = 'Fail' OR EMP_With_Failure.EMP_NAME IS NULL ) t
WHERE RowNumber = 1

此查询将过滤掉任何有失败用户的成功记录,您仍需要过滤结果集以获得每个用户只有一条记录