有表 table1 如下:F1     F2     F3    F4
A1     X01    正   0001
A2     Y01    负   0002
A2     Y01    正   0003 
A2     Y05    正   0004
B3     Y02    正   0005
B3     Y02    负   0006
B3     Y02    负   0007
B3     Y03    正   0008欲得到如下结果:F1     F2     F3    F4
A1     X01    正   0001
A2     Y05    正   0004
B3     Y02    负   0007
B3     Y03    正   0008要求 有相同F1,F2的记录如存在不同的F3 则正负抵消掉,求抵消后剩下的记录

解决方案 »

  1.   

    with t(f1, f2, v) as (
    select f1, f2, sum(decode(f3, '正', 1, -1)) from table1
           group by f1,f2
    )
    select f2,f2,f3,f4 from (
    select table1.*, t.v,
     row_number() over (partition by table1.f1, table1.f2, f3 order by f4 desc) rn
     from table1 join t on table1.f1=t.f1 and table1.f2=t.f2) t2
    where t2.v<>0
      and t2.f3=(case when t2.v>0 then '正' else '负' end)
      and t2.rn<=abs(t2.v);
      

  2.   

    假设表名为fooWITH T AS
    (SELECT A.F1,
           A.F2,
           A.F3,
           A.F4,
           RANK() OVER(PARTITION BY A.F1, A.F2, A.F3 ORDER BY A.F4) AS NUM
      FROM FOO A)
    SELECT  A.F1,A.F2,A.F3,A.F4 
        FROM T A 
    WHERE NOT EXISTS(SELECT 1 FROM T B WHERE A.F1=B.F1 AND A.F2=B.F2 AND A.NUM=B.NUM AND A.F3<>B.F3)
    ORDER BY 1;
      

  3.   

    with t(f1, f2, v) as (
    select f1, f2, sum(decode(f3, '正', 1, -1)) from table1
           group by f1,f2
    )
    select f2,f2,f3,f4 from (
    select table1.*, t.v,
     row_number() over (partition by table1.f1, table1.f2, f3 order by f4 desc) rn
     from table1 join t on table1.f1=t.f1 and table1.f2=t.f2) t2
    where t2.v<>0
      and t2.f3=(case when t2.v>0 then '正' else '负' end)
      and t2.rn<=abs(t2.v);