Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 比较不同列和行中的值_Sql_Sql Server - Fatal编程技术网

Sql 比较不同列和行中的值

Sql 比较不同列和行中的值,sql,sql-server,Sql,Sql Server,我有下表: ID COl1 COl2 1 13 15 2 13 16 3 13 17 4 17 13 我需要的是选择Col1值在Col2中可用的所有行,反之亦然 在这种情况下,只应返回第4行或第3行。它们具有相同的值(13 17) 假设col1是买方,col2是卖方 我想知道谁是互相买卖的用户。 如果用户a从用户b处购买,用户b应该从用户a处购买,以便退回。这听起来像是存在: select t.* from t where exists (select 1 fr

我有下表:

ID COl1 COl2
1  13    15
2  13    16
3  13    17
4  17    13
我需要的是选择
Col1
值在
Col2
中可用的所有行,反之亦然

在这种情况下,只应返回第4行或第3行。它们具有相同的值(13 17)

假设
col1
是买方,
col2
是卖方

我想知道谁是互相买卖的用户。
如果用户a从用户b处购买,用户b应该从用户a处购买,以便退回。

这听起来像是
存在

select t.*
from t
where exists (select 1 from t t2 where t2.col1 = t.col2) and
      exists (select 1 from t t2 where t2.col2 = t.col1) ;
select t.*
from t
where exists (select 1 from t t2 where t2.col1 = t.col2 AND t2.col2 = t.col1) ;
如果要将它们放在同一行中,我仍然会使用
exists

select t.*
from t
where exists (select 1 from t t2 where t2.col1 = t.col2) and
      exists (select 1 from t t2 where t2.col2 = t.col1) ;
select t.*
from t
where exists (select 1 from t t2 where t2.col1 = t.col2 AND t2.col2 = t.col1) ;

我建议使用自联接,因为如果双方都有多个买家和卖家的示例,它将不会生成多行。

这可以通过使用子查询来完成:

SELECT
    a.*
FROM
    yourTable   a
INNER JOIN
    yourTable   b
        ON  a.Col1 = b.Col2
        AND a.Col2 = b.Col1
        AND a.id  != b.id
SELECT ID, COl1, COl2
FROM table1 WHERE COl1 IN (SELECT DISTINCT COl2 FROM table1)
UNION
SELECT ID, COl1, COl2
FROM table1 WHERE COl2 IN (SELECT DISTINCT COl1 FROM table1)
这同样有效

SELECT * FROM your_table WHERE
col1 IN (SELECT col2 FROM your_table) 
AND 
col2 IN (SELECT col1 FROM your_table);

@scryptopath-那么您的查询有一个输入错误,或者您的数据与问题中的数据不同(只有在col1中某个地方有一个16时,才会返回第2行)。是的,col1中某个地方有一个16,但col2不是13。我需要和13 17-17一样的箱子13@Scryptopath . . . 我不是这样解释这个问题的。根本不清楚您是否希望结果在同一行中,而您最初的打字错误正好相反。您的解决方案不尊重从对方那里购买结果的目标。如果我们在col1中有13个,在col2中有17个,那么在另一行中,我们应该在col1中有17个,在col2中有13个