如何在PL / SQL中获取某些大小写的最大值

时间:2014-04-04 21:30:03

标签: sql oracle

我有一个类似的表数据:

作业类型作业名称任务否是_NO
A ----------- X ---------- 1 -------- N
A ----------- X ---------- 2 -------- N
A ----------- X ---------- 3 -------- Y
A ----------- X ---------- 4 -------- Y
A ----------- X ---------- 5 -------- N
B ----------- Z ---------- 1 -------- N
B ----------- Z ---------- 2 -------- N
B ----------- Z ---------- 3 -------- N

期望的结果应该是:

作业类型作业名称任务否是_NO

A ------------ X ---------- 4 --------- Y
B ------------ Z ---------- 3 -------- N

但我不能成功获得这些线

案例: 如果Yes_NO值为' Y',则为每个作业类型和作业名称获取最大task_no 和 如果Yes_NO值不是' Y' 获取每个作业类型和作业名称的最大任务编号

我尝试这样的事情:

Select Job_Type,Job_Name,Yes_NO,max(Task No)
From Table
where  Yes_NO='Y'
Group By  Job_Type,Job_Name,Yes_NO
UNION
Select Job_Type,Job_Name,Yes_NO,max(Task No)
From Table
where  not exists(Select 1
From Table
where  Yes_NO='Y')
Group By  Job_Type,Job_Name,Yes_NO

我的错在哪里或者有更简单的方法吗?

非常感谢。

3 个答案:

答案 0 :(得分:0)

试试这个:

Select Job_Type,Job_Name,Yes_NO,max(Task No)
From Table
where  Yes_NO='Y'
Group By  Job_Type,Job_Name,Yes_NO
UNION
Select t1.Job_Type,t1.Job_Name,t1.Yes_NO,max(t1.Task No)
From Table t1
  Left Join (select distinct Job_Type,Job_Name
             from Table where Yes_NO = 'Y'
            ) t2
    on t2.Job_Type = t1.Job_Type
    and t2.Job_Name = t1.Job_Name
Where t2.Job_Type is null
Group By  t1.Job_Type,t1.Job_Name,t1.Yes_NO

答案 1 :(得分:0)

您可以使用FIRST / LAST聚合函数或ROW_NUMBER分析函数来简化此操作。

select job_type, max(job_name), 
       max(task_no) keep (
         dense_rank first order by
         case when yes_no = 'Y' then 1 else 2 end,
         task_no desc
         ),
        max(yes_no) keep (
         dense_rank first order by
         case when yes_no = 'Y' then 1 else 2 end
         )
from t_table
group by job_type;

select job_type, job_name, task_no, yes_no
from (
  select job_type, job_name, task_no, yes_no,
  row_number() over (partition by job_type
                     order by case when yes_no = 'Y' then 1 else 2 end,
                     task_no desc
                     ) r
  from t_table
  )
where r = 1;

结果:

| JOB_TYPE | JOB_NAME | TASK_NO | YES_NO |
|----------|----------|---------|--------|
|        A |        X |       4 |      Y |
|        B |        Z |       3 |      N |

Fiddle

答案 2 :(得分:0)

这在SQL Fiddle中对我有用。

http://sqlfiddle.com/#!4/fa5b7/6

select a."Job Type", a."Job Name", max("Task No") as Task_No, b.Yes_No
from maxvalueexample a
inner join (select "Job Type", "Job Name", max("Yes_NO") as Yes_No
             from maxvalueexample
              group by "Job Type", "Job Name")b
        on b."Job Type" = a."Job Type"
        and b."Job Name" = a."Job Name"
        and b.Yes_No = a."Yes_NO"
group by a."Job Type", a."Job Name", b.Yes_No