我需要一些可以跳过'对的Oracle查询的帮助。并且只选择非配对数据。例如:
Id cost hour type
123 $1.00 1 Input
123 $1.00 1 Output
234 $2.00 4 Input
345 $5.00 4 Output
236 $3.00 5 Input
236 $3.00 3 Output
在这个例子中,前两行是'对,因为前3个字段匹配;第3和第4行,第5行和第6行不是'对,因为它们的前三个字段不匹配。
答案 0 :(得分:0)
您可以使用窗口功能和分区
select id, cost, hour, type
from (
select id, cost, hour, type,
count(*) over(partition by id, cost, hour) as cn
from mytable) t
where cn=1;
答案 1 :(得分:0)
我更改了列名"小时"到"小时"和"键入"到"键入_" (将保留的Oracle单词用作对象名称(包括列名称)并不好。我假设成本是一个数字,而不是显示的$符号。 (如果它是一个字符串,开头就是一个坏主意。)
with
input_data ( id, cost, hours, type_ ) as (
select 123, 1.00, 1, 'Input' from dual union all
select 123, 1.00, 1, 'Output' from dual union all
select 234, 2.00, 4, 'Input' from dual union all
select 345, 5.00, 4, 'Output' from dual union all
select 236, 3.00, 5, 'Input' from dual union all
select 236, 3.00, 3, 'Output' from dual
),
prep ( id, cost, hours, type_, rn, pairs ) as (
select id, cost, hours, type_,
row_number() over (partition by id, cost, hours, type_ order by null),
least ( count(case when type_ = 'Input' then 1 end)
over (partition by id, cost, hours),
count(case when type_ = 'Output' then 1 end)
over (partition by id, cost, hours)
)
from input_data
)
select id, cost, hours, type_
from prep
where rn > pairs
;
row_number()
计算固定ID,费用,小时数和类型_的行数(我不在乎什么顺序,我只需要它们"枚举")和{{1}计算有多少对。在最终选择中,我只保留row_number大于pairs
的行 - 这正是您所需要的。
pairs
答案 2 :(得分:0)
lag()
分析功能就足够了。
select * from stackovf svf where id not in (select id from (select svf.*,
(case when lag(id) over (partition by id,cost,hour order by 1)=id
and lag(cost) over (partition by id,cost,hour order by 1)=cost
and lag(hour) over (partition by id,cost,hour order by 1)=hour then 1
else 0 end )as match_found
from stackovf svf)
where match_found=1)