如果同一登录ID有两个值,如何删除某些行

时间:2014-06-09 10:41:33

标签: sql sql-server-2008

loginid       Status
========================
jo            deleted
jo            active
jo            discard
kir           active
user1         active
user1         deleted

结果应该只给我

kir      active

休息登录ID不应该在那里。

您能否请求查询

4 个答案:

答案 0 :(得分:1)

这应该可以解决问题:

select *
from yourtable
where loginid in
(select loginid
 from yourtable
 group by loginid
 having count([Status]) = 1) 

HAVING子句确保只选择映射了loginidStatus的{​​{1}}个值。请注意,此查询仅选择所需的行。如果要删除有问题的行,可以这样做:

delete 
from yourtable
where loginid in
(select loginid
 from yourtable
 group by loginid
 having count([Status]) > 1)

答案 1 :(得分:0)

试试这个:

DELETE
FROM login_table
WHERE login_id IN
  (SELECT login_id FROM login_table GROUP BY login_id HAVING COUNT(login_id)>1
  );

答案 2 :(得分:0)

缺少规则,但试试这个:

它返回没有其他状态而不是活动状态的所有loginid。

SELECT
    t.loginid
    ,t.Status
FROM
    table t
    LEFT JOIN 
        (SELECT
            loginid       
        FROM
            table
        WHERE
            Status <> 'active') loginDuplicatedAndNotActive
    ON t.loginid = loginDuplicatedAndNotActive.loginid
WHERE
    loginDuplicatedAndNotActive.loginid IS NULL
    AND t.Status = 'active'

答案 3 :(得分:0)

试试这个

DELETE  si
FROM    Tbl si
JOIN    (
        SELECT  login_id,Count(status)
        FROM    tbl
        GROUP BY
                login_id 
        HAVING  COUNT(status) > 1
        ) q
ON      q.login_id = si.login_id

<强> FIDDLE DEMO