我有一组数据,列x和y。这个集合包含行,对于任何2个给定值,A和B,在x和y列中分别有一行A和B,并且在x和y列中将分别有第二行B和A.
E.g
**Column X** **Column Y**
Row 1 A B
Row 2 B A
我需要一个T-Sql查询,给出一个带有上述规则的集合将返回第1行或第2行,但不能同时返回两者。
要么答案非常困难,要么就这么容易让我看不到森林里的树木,无论是哪种方式都让我爬上了墙。
答案 0 :(得分:9)
在谓词中添加谓词
where X < Y
你永远不会得到第二行,但总会得到第一行。
(这假定当您编写“两个给定值”时,您意味着两个不同给定值;如果两个值可以相同,则添加谓词where X <= Y
(以摆脱所有“反转”行,其中X> Y)然后将distinct
添加到您的选择列表中(将X == Y的任意两行折叠成一行)。)
回复评论:
也就是说,如果您的查询目前为select foo, x, y from sometable where foo < 3;
,则将其更改为select foo, x, y from sometable where foo < 3 and x < y;
,或者针对第二种情况(其中X和Y不是不同的值)select distinct foo, x, y from sometable where foo < 3 and x <= y;
。
答案 1 :(得分:1)
这应该有用。
Declare @t Table (PK Int Primary Key Identity(1, 1), A int, B int);
Insert into @t values (1, 2);
Insert into @t values (2, 1);
Insert into @t values (3, 4);
Insert into @t values (4, 3);
Insert into @t values (5, 6);
Insert into @t values (6, 5);
Declare @Table Table (ID Int Primary Key Identity(1, 1), PK Int, A Int, B Int);
Declare @Current Int;
Declare @A Int;
Insert Into @Table
Select PK, A, B
From @t;
Set @Current = 1;
While (@Current <= (Select Max(ID) From @Table) Begin
Select @A = A
From @Table
Where ID = @Current;
If (@A Is Not Null) Begin
Delete From @Table Where B = @A;
If ((Select COUNT(*) From @Table Where A = @A) > 1) Begin
Delete From @Table Where ID = @Current;
End
End
Set @A = Null;
Set @Current = @Current + 1;
End
Select a.*
From @tAs a
Inner Join @Table As b On a.PK = b.PK
答案 2 :(得分:0)
要获得每对中的最高和最低,您可以使用:
(X+Y+ABS(X-Y)) / 2 as High, (X+Y-ABS(X-Y)) / 2 as Low
所以现在使用DISTINCT获取它们的对。
SELECT DISTINCT
(X+Y+ABS(X-Y)) / 2 as High, (X+Y-ABS(X-Y)) / 2 as Low
FROM YourTable
答案 3 :(得分:0)
SELECT O.X, O.Y
FROM myTable O
WHERE EXISTS (SELECT X, Y FROM myTable I WHERE I.X = O.Y AND I.Y = O.X)
我没试过这个。但是,这应该有用。