我的目标是在资产列表中识别不同帐户的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小提琴:http://sqlfiddle.com/#!2/c7e6d
我尝试过GROUP BY,HAVING和COUNT,但到目前为止我还没有成功。 这个问题是否可以解决SQL问题?
任何帮助将不胜感激!
答案 0 :(得分:2)
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)
答案 1 :(得分: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)
答案 2 :(得分: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)
答案 3 :(得分:0)
SELECT Personnel_ID, Sequence_Nr, Personnel_Name, Title
FROM Persons
GROUP BY Personnel_ID, Sequence_Nr, Personnel_Name, Title
类似的sql语句应该做你期望的事情