在sql中找到记录之间的差异

时间:2015-11-12 03:35:56

标签: sql sql-server

查询:

with cte as (
      select sb.case, sb.Trace, sb.Amount, sp.edge, sp.UserId,
             count(*) over (partition by sp.edge) as cnt
      from Budget sb join
           Sap sp 
           on sb.Trace = sp.Trace
      where sb.Trace in (select Trace from Sap where sb.UserId in ('R5', 'HB'))
     )
select cte.*
from cte
where cnt > 1
order by edge desc;

生成以下输出:

case        trace       amount  edge        userId                  cnt
110000061   40902752    357.00  21182786    HB                      2
110000061   40863651    161.00  21182786    R5                      2 

现在,我只需要显示那些与金额不同的情况。

例如: R5用户数量&lt; = HB用户数量-10 即if (161<=[357-10])然后显示案例 有人可以告诉我吗?

1 个答案:

答案 0 :(得分:0)

所以你已经知道你将处理2个特定的UserIds?

如果是,您可以将您发布的结果放入临时表中,然后将其加入自身...... 所以#TMP会包含..

case        trace       amount  edge        userId                  cnt
110000061   40902752    357.00  21182786    HB                      2
110000061   40863651    161.00  21182786    R5                      2 

然后通过这个得到你想要的东西....

SELECT * FROM #TMP T1
INNER JOIN #TEMP T2 ON T2.case = T1.case
WHERE
ABS(ABS(T1.amount) - ABS(T2.AMOUNT)) >= 10   --A difference of 10 or more