在SQL Server 2014中获取JOIN上的重复项

时间:2017-06-07 17:17:01

标签: sql sql-server

我的表:

帐户A
板P
FinTransMaster F
TollTrans T

关系:

A.AccountId = P.AccountId  
A.AccountId = F.AccountId  
A.AccountId = P.AccountId = F.AccountId  
P.LicPlateNo = T.LicPlateNo  

T.AccountId != A.AccountId  
T.AccountId != P.AccountId  
T.AccountId != F.AccountId 

我需要所有记录:

     T.AccountId = '123456'   
 AND EXISTS F.TransCode = 'TOLL'   
 AND NOT EXISTS F.TransCode = 'PYMT'
 AND A.CurrentBalance > 0

到目前为止我的代码:

SELECT A.*

FROM Account A
INNER JOIN Plate P ON P.AccountId = A.AccountId
INNER JOIN TollTrans T ON T.LicPlateNo = P.LicPlateNo

WHERE EXISTS     (SELECT 1
                  FROM FinTransMaster F
                  WHERE F.AcctID = A.AccountID AND F.TransCode = 'TOLL'
                  ) 
  AND NOT EXISTS (SELECT 1
                  FROM FinTransMaster F
                  WHERE F.AcctID = A.AccountID AND F.TransCode = 'PYMT'
                  )
  AND T.AccountId = '123456'
  AND A.CurrentBalance > 0

ORDER BY BalanceDT DESC

每个帐户都有一个车牌。某些帐户有多个许可证板。也许,这就是我得到重复的原因。

如何优化此代码?

3 个答案:

答案 0 :(得分:1)

使用

select distinct a.col1,a.col2....
(rest of the query)

另外,看看你是否可以用exists替换join,因为你没有从其他表中选择任何东西,所以性能会更好。

答案 1 :(得分:1)

您可以使用不同的

删除
SELECT distinct A.*
FROM Account A
INNER JOIN Plate P ON P.AccountId = A.AccountId
INNER JOIN TollTrans T ON T.LicPlateNo = P.LicPlateNo
INNER JOIN FinTransMaster F on F.AcctID = A.AccountID AND F.TransCode = 'TOLL'
WHERE NOT EXISTS (SELECT *
                  FROM FinTransMaster G
                  WHERE G.AcctID = A.AccountID AND G.TransCode = 'PYMT'
                  )
AND T.AccountId = '123456' AND A.CurrentBalance > 0
ORDER BY BalanceDT DESC

答案 2 :(得分:1)

如果您只对Account表感兴趣,只需将其他表移到EXISTS子查询中:

SELECT *
FROM Account A
WHERE EXISTS     (SELECT 1
                  FROM FinTransMaster F
                  WHERE F.AcctID = A.AccountID AND F.TransCode = 'TOLL'
                  ) 
  AND NOT EXISTS (SELECT 1
                  FROM FinTransMaster F
                  WHERE F.AcctID = A.AccountID AND F.TransCode = 'PYMT'
                  )
  AND EXISTS      (SELECT 1
                  FROM Plate P
                  INNER JOIN TollTrans T ON T.LicPlateNo = P.LicPlateNo
                  WHERE P.AccountId = A.AccountId
                    AND T.AccountId = '123456'
                  )
  AND A.CurrentBalance > 0
ORDER BY BalanceDT DESC

如果BalanceDT不在帐户表格中,那么您就无法做到这一点,但是,您没有对该列进行限定。