【发布时间】:2015-08-04 21:35:45
【问题描述】:
我编写了一个 SQL 查询来过滤多个条件,并使用 distinct 来仅查找唯一记录。
具体来说,我只需要AccountID 字段是唯一的,每个AccountID 有多个AddressClientIDs。
查询有效,但产生了一些重复。
进一步的警告是:
- 每个
AccountID有多个trans -
Y和N都可以有跨记录,AccountID
我只想返回AccountIDs,它具有指定状态以外的状态,因此我不使用,因为我不想要这两种状态。
我只想找到 AccountID 列的唯一值。
如果有人可以帮助完善下面的查询,将不胜感激。
SELECT AFS_Account.AddressClientID
,afs_transunit.AccountID
,SUM(afs_transunit.Units)
FROM AFS_TransUnit
,AFS_Account
WHERE afs_transunit.AccountID IN (
-- Gets accounts which only have non post statuses
SELECT DISTINCT accountid
FROM afs_trans
WHERE accountid NOT IN (
SELECT accountid
FROM afs_trans
WHERE STATUS IN (
'POSTPEND'
,'POSTWAIT'
)
)
-- This gets the unique accountIDs which only have transactions with Y status,
-- and removes any which have both Y and N.
AND AccountID IN (
SELECT DISTINCT accountid
FROM afs_trans
WHERE IsAllocated = 'Y'
AND accountid NOT IN (
SELECT DISTINCT AccountID
FROM afs_trans
WHERE IsAllocated = 'N'
)
)
)
AND AFS_TransUnit.AccountID = AFS_Account.AccountID
GROUP BY afs_transunit.AccountID
,AFS_Account.AddressClientID
HAVING SUM(afs_transunit.Units) > 100
谢谢。
【问题讨论】:
-
设置 sqlfiddle 将有助于调试您的问题。 sqlfiddle.com
-
另外:您使用的是哪个 DBMS?后格雷斯?甲骨文?
-
此连接上的两个表之间是否是一对一关系:
AFS_TransUnit.AccountID = AFS_Account.AccountID? -
@jpw 不用担心!我猜这两个表之间存在一对多的关系。所以,我只是想与 OP 确认这是不是真的。
-
@a_horse_with_no_name - 我正在使用 MS SQL Server。
标签: sql sql-server database duplicates