用于标识哪些帐号具有多个代理的sql

时间:2014-10-21 20:58:28

标签: sql sql-server

我不认为计数会在这里工作,有人可以帮我找一个sql来识别哪个帐号有多个代理,两个以上的代理在where条件下。

    AGENT_NAME          ACCOUNT_NUMBER

    Clemons, Tony       123
    Cipollo, Michael    123
    Jepsen, Sarah       567
    Joanos, James       567
    McMahon, Brian      890
    Novak, Jason        437
    Ralph, Melissa      197
    Reitwiesner, John   221
    Roman, Marlo        123
    Rosenzweig, Marcie  890

结果应该是这样的。

ACCOUNT_NUMBER    AGENT_NAME         
123               Cipollo, Michael
123               Roman, Marlo
123               Clemons, Tony      
890               Rosenzweig, Marcie
890               McMahon, Brian
567               Joanos, James
567               Jepsen, Sarah 

3 个答案:

答案 0 :(得分:1)

您可以使用窗口功能执行此操作:

select t.account_number, t.agent_name
from (select t.*, min(agent_name) over (partition by account_number) as minan,
             max(agent_name) over (partition by account_number) as maxan
      from table t
     ) t
where minan <> maxan;

如果您知道代理名称永远不会重复,您可以这样做:

select t.account_number, t.agent_name
from (select t.*, count(*) over (partition by account_number) as cnt
      from table t
     ) t
where cnt > 1;

答案 1 :(得分:0)

假设您的表名是test,这应该提取所有重复ACCOUNT_NUMBER的记录:

select * from test where ACCOUNT_NUMBER in 
       (select ACCOUNT_NUMBER from test 
           group by ACCOUNT_NUMBER having 
        count(ACCOUNT_NUMBER)>1)
order by ACCOUNT_NUMBER

答案 2 :(得分:0)

使用计数功能你可以得到结果

CREATE TABLE #TEMP
  (
     AGENT_NAME     VARCHAR(100),
     ACCOUNT_NUMBER INT
  )

INSERT INTO #TEMP
VALUES      ('CLEMONS, TONY',123),
            ('CIPOLLO, MICHAEL',123),
            ('JEPSEN, SARAH',567),
            ('JOANOS, JAMES',567),
            ('MCMAHON, BRIAN',890),
            ('NOVAK, JASON',437),
            ('RALPH, MELISSA',197),
            ('REITWIESNER, JOHN',221),
            ('ROMAN, MARLO',123),
            ('ROSENZWEIG, MARCIE',890)

SELECT a.ACCOUNT_NUMBER,a.AGENT_NAME
FROM   #TEMP A
       JOIN(SELECT COUNT(1) CNT,
                   ACCOUNT_NUMBER
            FROM   #TEMP
            GROUP  BY ACCOUNT_NUMBER) B
         ON A.ACCOUNT_NUMBER = B.ACCOUNT_NUMBER
WHERE  B.CNT != 1