Mysql SQL:在资产列表中查找不同的帐户

Mysql SQL:在资产列表中查找不同的帐户,mysql,sql,select,Mysql,Sql,Select,我的目标是使用SQL语句在资产列表中标识不同的帐户(资产有一个主编号和一个子编号) 该表如下所示: amainnr | asubnr | account ----------------------------- 10000 | 0 | 123 10000 | 1 | 123 10000 | 2 | 456 10000 | 3 | 789 10001 | 0 | 123 10001 | 1 | 123 10001

我的目标是使用SQL语句在资产列表中标识不同的帐户(资产有一个主编号和一个子编号)

该表如下所示:

amainnr | asubnr | account
-----------------------------
10000   | 0      | 123
10000   | 1      | 123
10000   | 2      | 456
10000   | 3      | 789
10001   | 0      | 123
10001   | 1      | 123
10001   | 2      | 123
10002   | 0      | 123
10003   | 0      | 456
10004   | 0      | 123
10005   | 0      | 123
10005   | 1      | 456
因此,我需要一个包含所有行的表,其中mainnr存在不同的帐户,例如:

amainnr | asubnr | account
-----------------------------
10000   | 0      | 123
10000   | 1      | 123
10000   | 2      | 456
10000   | 3      | 789
10005   | 0      | 123
10005   | 1      | 456
我用这个表创建了一个SQL FIDLE:

我尝试了很多与小组,有和计数,但到目前为止,我没有成功。 这个问题可以用SQL解决吗

任何帮助都将不胜感激

试试这个:

SELECT b.amainnr,
       b.asubnr,
       b.account
FROM atable b
WHERE b.amainnr IN
    (SELECT a.amainnr
     FROM atable a
     GROUP BY a.amainnr HAVING count(distinct(a.account)) > 1)
    select * from atable a
    where exists (select 1 from atable b 
                     where a.id!=b.id 
                       and a.amainnr = b.amainnr 
                       and a.account != b.account)
试试这个:

    select * from atable a
    where exists (select 1 from atable b 
                     where a.id!=b.id 
                       and a.amainnr = b.amainnr 
                       and a.account != b.account)
类似的sql语句应该满足您的期望


类似的sql语句应该完成您期望的任务

此任务可以通过以下代码完成:

SELECT new.amainnr, new.asubnr, new.account

FROM [table_name] as new

WHERE new.amainnr IN (SELECT old.amainnr
                                       FROM [table_name] as old
                                          GROUP BY old.amainnr HAVING count(distinct (old.account)) > 1)

此项工作可通过以下代码完成:

SELECT new.amainnr, new.asubnr, new.account

FROM [table_name] as new

WHERE new.amainnr IN (SELECT old.amainnr
                                       FROM [table_name] as old
                                          GROUP BY old.amainnr HAVING count(distinct (old.account)) > 1)