我想选择某些列和其他列的值相等,
您可以在下面显示示例,
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
所以输出为真。
如何创建此选择查询。
感谢您的关注。
答案 0 :(得分: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必须是NOT EQUAL,那么查询应该是
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)