2016-03-02 38 views
-2

我想选择约值一些列等栏目相等,T-SQL选择一些列关于范围

您可以显示下面的例子,

ID  A_Col  B_Col  C_Col  D_Col 
1  15  36   1100  1650 
2  15  36   1115  1900 
3  19  38   1100  1750 
4  15  36   900   1925 

这个例子A和B列等于但是C或D列不相等,2%的范围不同。

所以下面

ID  A_Col  B_Col  C_Col  D_Col 
1  15  36   1100  1650 
2  15  36   1115  1900 
4  15  36   900   1925 
  • 第一和第二行的大约%A和B列等于和C_Column差1,3-
  • 2ST和第四行的A和B列等于和d柱该表输出差异大约为%1,6

所以这个输出是真的。

我如何创建此选择查询。

感谢您的关注。

+0

如果我添加数据'(5,15,38,1100,1400),(6,15,38,1120,1600),(7,15,31,1300,1610)',会发生什么? – Susilo

回答

0

此致例子(我加了一些值)

declare @T table (ID int, A_Col int,  B_Col int,  C_Col int,  D_Col int) 

insert @T 
values (1,15,36,1100,1650) 
,(2,15,36,1115,1900) 
,(3,19,38,1100,1750) 
,(4,15,36,900,1925) 
,(5,15,36,1900,2925) 
,(6,15,36,1900,2930) 


select * from @T T 
where exists( 
      select 1 from @T 
      where ID <> T.ID 
      and D_Col <> T.D_Col 
      and C_Col <> T.C_Col 
      and A_Col = T.A_Col 
      and B_Col = T.B_Col 
      and ( 
        CONVERT(float,C_Col)/T.C_Col between 0.98 and 1.02 
        or 
        CONVERT(float,D_Col)/T.D_Col between 0.98 and 1.02) 
    ) 

给我们结果

(6 row(s) affected) 
ID   A_Col  B_Col  C_Col  D_Col 
----------- ----------- ----------- ----------- ----------- 
1   15   36   1100  1650 
2   15   36   1115  1900 
4   15   36   900   1925 

(3 row(s) affected) 

如果不要求d和C必须不等于那么查询应该是

select * from @T T 
    where exists( 
       select 1 from @T 
       where ID <> T.ID 
       and A_Col = T.A_Col 
       and B_Col = T.B_Col 
       and ( 
         CONVERT(float,C_Col)/T.C_Col between 0.98 and 1.02 
         or 
         CONVERT(float,D_Col)/T.D_Col between 0.98 and 1.02) 
     ) 

和结果

(6 row(s) affected) 
ID   A_Col  B_Col  C_Col  D_Col 
----------- ----------- ----------- ----------- ----------- 
1   15   36   1100  1650 
2   15   36   1115  1900 
4   15   36   900   1925 
5   15   36   1900  2925 
6   15   36   1900  2930 

(5 row(s) affected)