SQL Query返回多个重复结果

时间:2014-02-18 19:21:10

标签: sql sql-server database sql-server-2008 join

场景:我有三个表(囚犯,AddPaymentTransaction,WithdrawPaymentTransation) 表格中的日期:我有1排囚犯,其中PrisonerID = 5,另外两行中有两行, 如果有任何囚犯在那个帐户中添加了一些付款,或者在同一天或不同日期等时从那里付款,我已经写了查询以返回数据。

这是我的查询:

select  at.PrisonerID ,at.Amount as AAmount,at.Date as ADate,wt.Amount as WAmount,wt.Date as WDate 
from Prisoners p, AddPaymentTransaction at,WithdrawPaymentTransation wt 
where p.PrisonerID=at.PrisonerID and p.PrisonerID=wt.PrisonerID and at.PrisonerID=wt.PrisonerID and at.PrisonerID=5

但是当我在每个表中有3行数据时,它给了我4行9行。 我希望数据行没有重复。任何建议或帮助将受到高度赞赏。

1 个答案:

答案 0 :(得分:1)

您的查询中的at.PrisonerID = wt.PrisonerID可能是造成所有重复项的原因。我猜测AddPaymentTransactionWithdrawPaymentTransation不应该联系在一起。那么,以下内容如何:

SELECT at.PrisonerID, at.Amount as AAmount, at.Date as ADate,
       wt.Amount as WAmount, wt.Date as WDate 
FROM Prisoners p 
INNER JOIN AddPaymentTransaction at p.PrisonerID = at.PrisonerID 
INNER JOIN WithdrawPaymentTransation wt ON p.PrisonerID = wt.PrisonerID
WHERE at.PrisonerID = 5

但这可能不会给你你正在寻找的东西。所以可能类似以下内容:

SELECT * FROM 
(
  SELECT p.PrisonerID, 'AddPayment' AS Type, 
         apt.Amount as TransAmount, apt.Date AS TransDate
  FROM Prisoners p 
  INNER JOIN AddPaymentTransaction apt ON p.PrisonerID = apt.PrisonerID 
  WHERE apt.PrisonerID = 5

  UNION

  SELECT p.PrisonerID, 'WithdrawPayment' AS Type, 
         wt.Amount as TransAmount, wt.Date as TransDate 
  FROM Prisoners p 
  INNER JOIN WithdrawPaymentTransation wt ON p.PrisonerID = wt.PrisonerID
  WHERE wt.PrisonerID = 5
) AS mq
ORDER BY mq.TransDate DESC