问题描述
我是PL-sql的新手。我有一个包含数千个文件信息记录的表(摘录如下所示)。对于同一个任务,我需要比较两个文件A和B,以检查task_name是否相同或不同。例如,在下表中,文件A任务10与文件B任务10具有相同的task_name(xx),而文件A任务20与文件B任务20具有不同的task_name。我应该能够标记这些区别和相似之处。我想在一个游标中使用一个游标来循环并比较这些值,但是我不知道该怎么做。我当前正在使用oracle11。谢谢
File Task Task_name
A 10 xx
A 20 xy
A 30 xz
B 10 xx
B 20 xz
**编辑
感谢您的回复。我需要循环的原因是因为最后我需要显示结果 使用以下格式的clob变量。所以我需要在迭代中捕获任务编号和任务名称 显示在clob变量中
------文件比较---------
不同的任务名称
相同的任务名称
任务10:任务名称xx
解决方法
您不需要使用PL / SQL,而是通过将COUNT(..) OVER (..)
子句与{一起使用,将SQL与Task
和Task_name
列分组的PARTITION BY
分析函数一起使用{1}}条件表达式就足够了,例如
CASE..WHEN
,
您还可以使用operator EXISTS
。EXISTS运算符与子查询一起使用,以测试是否存在行。
尽管在您的问题中没有提及A / B中的重复项,但是您可以使用通用查询在同一组或不同 /
中查找重复项还应注意以下事实,即当仅在一个文件组内复制(例如,仅在A中)时,该查询返回正确的结果:
--using cte to set row's number
with cte as
(
select *,row_number()over (order by Task,TaskName)num from Table
)
select File,Task,TaskName,case
--using t1.num<>t2.num because current row can refer to itself
when exists (select 1 from cte t1 where t1.Task=t2.Task and
t1.Taskname=t2.TaskName and t1.num<>t2.num)
then 'Duplicate'
else
'No Duplicate'
end as flag
from cte t2
如果在表中一个文件组中没有重复项,而您只需要查找A和B文件组之间的差异,则可以使用此查询:
select File,case
when exists (select 1 from Table t1 where t1.Task=t2.Task and
t1.Taskname=t2.TaskName and t1.File<>t2.File)
then 'Duplicate'
else
'No Duplicate'
end as flag
from Table t2
您可以使用window function count
来对文件组中的Task和TaskName进行计数。但是首先,您需要删除每个组中的重复项,然后对值进行计数,就像在一个组中一样。
如果您需要比较两个文件A和B,则可以尝试以下查询:
Select File,TaskNane,case when countVal>1 then 'Duplicate' else 'No
Duplicate' and as flag
From
(
Select count(*)over (partition by file_gr,TaskName) countVal
From
(
--add new accessorial column as if there's one group
Select *,case when File='B' then 'A' else 'A' end as file_gr
From
(
--remove duplicate within each group A and B
Select distinct File,TaskName from Table
) X
) Y
) Z
,
with t (Files,Task_name ) as
(
select 'A',10,'xx' from dual union all
select 'A',20,'xy' from dual union all
select 'A',30,'xz' from dual union all
select 'B','xx' from dual union all
select 'B','xz' from dual
)
select t1.*,nvl((select 'Y' from t t2 where t2.files <> t1.files and t2.task = t1.task and t2.task_name = t1.task_name),'N') as is_same
from t t1
order by 1,2
输出:
,您可以按任务汇总以获取差异:
select
task,max(case when file = 'A' then task_name end) as task_file_a,max(case when file = 'B' then task_name end) as task_file_b
from mytable
where file in ('A','B')
group by task
having count(*) <> 2 or count(distinct task_name) <> 1
order by task;
您可以在PL / SQL中使用Cursor FOR LOOP
来使用它。这是草稿:
create or replace function get_diff return clob is
v_clob clob;
begin
for row in
(
select
task,max(case when file = 'B' then task_name end) as task_file_b,case when count(*) <> 2 or count(distinct task_name) <> 1
then 'diff'
else 'same'
end as diff_same
from mytable
where file in ('A','B')
group by task
order by diff_same,task
) loop
v_clob := v_clob + ...
end loop;
end;
您可以像这样访问行数据:'Task for file A is' || row.task_file_a
。
您将必须检查相同的/ diff,或者您只需要使用两个循环来处理差异,一个就用于相等性。