T-SQL - 查询过滤

时间:2013-08-28 11:19:13

标签: sql sql-server tsql

表1:

Id          Customer No_
7044900804  Z0172132
7044900804  Z0194585
7044907735  Z0172222
7044907735  Z0172222
7044910337  Z0172216
7044911903  Z0117392

我希望只从表1中获取相同ID和不同客户编号的值。

Id          Customer No_
7044900804  Z0172132
7044900804  Z0194585

我已经尝试使用查询来查找重复项,但它不会使用来自table1的相同的ID和相同的客户号_ 来过滤值。

SELECT  Id
      , [Customer No_]
  FROM table1
GROUP BY Id, [Customer No_]
HAVING COUNT(*) > 1

你能帮我解决 T-SQL 查询解决方案吗? 感谢您的所有建议。

5 个答案:

答案 0 :(得分:3)

试试这个

SELECT * FROM table1 WHERE Id IN
(
    SELECT  Id
      FROM table1
    GROUP BY Id
    HAVING COUNT(DISTINCT [Customer No_]) > 1
)

SQL FIDDLE DEMO

答案 1 :(得分:1)

我认为最简单的方法就是将表连接两次,其中ID已加入,但客户No_s不匹配。

select t1.id, t1.[customer No_], t2.[customer No_]
from table1 t1 
inner join table1 t2
on t1.id = t2.id
and t1.[customer No_] != t2.[customer No_]

答案 2 :(得分:0)

请尝试:

SELECT * FROM (
    SELECT 
        *, 
        COUNT(*) OVER (PARTITION BY id, [Customer No_]) C1, 
        COUNT(*) OVER (PARTITION BY id) C2 
    FROM 
        YourTable
)x WHERE C1<>C2

答案 3 :(得分:0)

尝试:

SELECT ID, [Customer No_]
FROM table1
WHERE ID IN (SELECT ID
             FROM table1
             GROUP BY ID
             HAVING count(*) > 1)

<强> SQL Fiddle

答案 4 :(得分:0)

查询:

SELECT t1.Id
      ,t1.[Customer No_]
FROM table1 t1
 JOIN (SELECT Id, COUNT(*) as cnt
       FROM table1 
       GROUP BY id)
 ON t1.id = t2.id
WHERE t2.cnt > 1