比较SQL查询结果

时间:2015-11-11 17:07:50

标签: sql sql-server

我有以下疑问。

查询1:

SELECT sb.number
     , sb.Trace
     , sb.Amount
     , sp.edge, sp.UserId
  FROM Budget sb JOIN SNAP sp ON sb.Trace = sp.Trace
 WHERE sb.Trace 
    IN (SELECT Trace FROM SNAP WHERE User='R5' )
 ORDER BY sp.edge DESC

输出:

number      Trace       Amount  Edge        UserId
111276509   40902337    30.00   21673074    R5
111276507   40902333    17.00   21673073    R5
111276505   40902331    29.00   21673071    R5

查询2:

SELECT sb.number
     , sb.Trace
     , sb.Amount
     , sp.edge,sp.UserId  
  FROM Budget sb JOIN SNAP sp ON sb.Trace = sp.Trace
 WHERE sb.Trace 
    IN (SELECT Trace FROM SNAP WHERE UserId<>'R5' )
 ORDER BY sp.edge DESC

输出:

number      Trace       Amount  Edge        UserId
111276509   50902337    20.00   21673074    App
111276507   50902333    50.00   21673073    App
111276505   50902331    70.00   21673071    App

现在,我只需要比较两个输出的Edge列,如果值相同,则应输出两个表中的相应记录。 例如:对于Edge值21673074,我应该

number      Trace       Amount  Edge        UserId
111276509   40902337    30.00   21673074    R5
111276509   50902337    20.00   21673074    App

1 个答案:

答案 0 :(得分:2)

一种方法使用窗口函数:

select sbp.*
from (select sb.number, sb.Trace, sb.Amount, sp.edge, sp.UserId,
             sum(case when User = 'R5' then 1 else 0 end) over (partition by trace) as num_R5,
             sum(case when User <> 'R5' then 1 else 0 end) over (partition by trace) as num_NotR5
      from Budget sb join
           SNAP sp 
           on sb.Trace = sp.Trace
     ) sbp
where num_R5 > 0 and num_NotR5 > 0
order by sp.edge desc;

另一个只是基于您的查询:

select sb.number, sb.Trace, sb.Amount, sp.edge, sp.UserId
from Budget sb join
     SNAP sp 
     on sb.Trace = sp.Trace
where sb.Trace in (select Trace from SNAP where User = 'R5' ) and
      sb.Trace in (select Trace from SNAP where User <> 'R5' )
order by sp.edge desc;

当然,两个exists中的一个是多余的,因为当前行自动匹配其中一个。您可以通过以下方式提高效率:

select sb.number, sb.Trace, sb.Amount, sp.edge, sp.UserId
from Budget sb join
     SNAP sp 
     on sb.Trace = sp.Trace
where (sp.User <> 'R5' and
       sb.Trace in (select Trace from SNAP where User = 'R5' )
      ) or
      (sp.User = 'R5' and
       sb.Trace in (select Trace from SNAP where User <> 'R5' )
      )
order by sp.edge desc;
相关问题