SQL获取这些唯一行

时间:2013-05-29 17:48:31

标签: sql sql-server-2008

有一张表,只需要输出某些行。这是一个例子:

表:

ID  Pacct   Sacct
----------------------
10  12  12
9   13  12
12  14  12
4   15  16
5   16  15
6   17  18
7   19  18

需要选择Pacct<>行只要存在Pacct = Sacct

的行,就进行Sacched

因此,对于上表,我正在寻找的输出将是:

ID  PAcct   Sacct
--------------------------
9   13  12
12  14  12

有关如何完成的任何想法?非常感谢!

5 个答案:

答案 0 :(得分:1)

您似乎希望成对的pacctsacct不同,sacct不在paccts列表中,而select * from t where pacct <> s.acct and s.acct in (select t2.pacct from t t2 and t2.sacct = t2.pacct) 两者相同:{{1}}

{{1}}

答案 1 :(得分:0)

你正在寻找这些方面的东西。但我不确定。

select *
from Table1 
inner join 
  (select D, Pacct, Sacct
   from Table1
   where Pacct = Sacct ) p_eq_s
on Table1.Pacct = p_eq_s.Sacct
or Table1.Pacct = p_eq_s.Pacct
or Table1.Sacct = p_eq_s.Sacct
or Table1.Sacct = p_eq_s.Pacct
where Table1.Pacct <> Table1.Sacct

答案 2 :(得分:0)

SELECT t1.ID, t1.PAcct, t1.Sacct
FROM MyTable t1
INNER JOIN MyTable t2
ON t2.ID <> t1.ID AND t2.PAcct = t1.PAcct
WHERE t1.PAcct <> t1.Sacct
AND t2.PAcct = t2.Sacct

请注意,这依赖于PAcct和Sacct不可为空(或者更改了关于空相等比较的默认SQL Server设置)。如果它们可以为空,则必须更改WHERE t1.PAcct <> t1.Sacct子句以解释此问题。

答案 3 :(得分:0)

试试这个

select * from table x1
where Pacct <> Sacct 
and exists (select 1 from table x2 
             where x2.Pacct = x2.Sacct and 
                  (x1.Pacct = x2.Pacct or 
                   x1.Sacct = x2.Sacct))        

SQL DEMO

答案 4 :(得分:-1)

你应该尝试类似的东西:

SELECT * FROM dump WHERE (PAcct - Sacct = 0);