选择相同的ID但在其他列中不同

时间:2017-10-04 08:08:08

标签: sql sql-server

嗨,请帮助我获得结果,其中必须在结果中包含具有不同输入的custids。请注意,不论多少次,具有相同输入的CustID都不得包含在内。

样本表

    +------+------+
    |CustID|Input |
    +------+------+
    |123   |A     |
    +------+------+
    |123   |B     |
    +------+------+

结果:

.git/hooks

谢谢!

3 个答案:

答案 0 :(得分:0)

可以通过多种方式完成,例如:使用3.6.3

EXISTS

SELECT DISTINCT CustID, Input FROM tablename t1 WHERE EXISTS (SELECT 1 FROM tablename t2 WHERE t1.CustID = t2.CustID AND t1.Input <> t2.Input) / IN

GROUP BY

根据预期结果选择SELECT DISTINCT CustID, Input FROM tablename WHERE CustID IN (SELECT CustID FROM tablename GROUP BY CustID HAVING COUNT(DISTINCT Input) > 1) SELECT DISTINCT,如果有重复项。

答案 1 :(得分:0)

请检查一下

    select CustID,input from my_table 
    group by input,CustID having max(rowid) 
in (select max(rowid) from emp group by deptno); 

答案 2 :(得分:0)

您想要Input的不同CustID计数大于1的记录。您还希望在重复的情况下获得不同的结果行。因此,首先要删除重复项,在每个CustID内计算并保留所需的记录:

select custid, input
from
(
  select custid, input, count(*) over (partition by custid) as cnt
  from (select distinct custid, input from mytable) m
) counted
where cnt > 1;

select top(1) with ties 
  custid, input
from (select distinct custid, input from mytable) m
order by case when count(*) over (partition by custid) = 1 then 1 else 2 end desc;