连接两个表后重复记录

时间:2014-06-09 03:53:32

标签: sql-server join

我目前在加入两个表后遇到查询问题我正在获取重复记录。我想要做的是从表1和表2中的付款记录获取相同日期的详细信息..这是我的查询。

SELECT dbo.tblautoipekonek.ipno,
       dbo.tblautoipekonek.awbno,
       dbo.tblautoipekonek.ipamount,
       dbo.tblautoipekonek.orno,
       dbo.tbladdfunds.username,
       dbo.tbladdfunds.newctfbal,
       dbo.tbladdfunds.addedctfamt,
       dbo.tbladdfunds.oldctfbal,
       dbo.tbladdfunds.newipbal,
       dbo.tbladdfunds.addedipamt,
       dbo.tbladdfunds.oldipbal,
       dbo.tbladdfunds.date,
       dbo.tblautoipekonek.date AS Expr1
FROM   dbo.tblautoipekonek

       LEFT OUTER JOIN dbo.tbladdfunds
                    ON dbo.tblautoipekonek.date = dbo.tbladdfunds.date
WHERE  
        ( dbo.tblautoipekonek.date = '06/06/2014' )  

3 个答案:

答案 0 :(得分:0)

您好,您可以使用" Distinct"关键字在"选择"关键词。它将获得单一记录。

很好用别名替换dbo.tablename,将tablename替换为

select 
      distinct      
      auto.IPNo, ... ---here you can add other column of this table.
      fund.AddedCTFAmt --same thing done here.

FROM         tblAutoIPEkonek auto

    LEFT OUTER JOIN  dbo.tblAddfunds  fund
        ON auto.Date = fund.Date   --try to add more join condition so filteration done here of data which is fastest/
    WHERE     (auto.Date = '06/06/2014')

答案 1 :(得分:0)

SELECT DISTINCT dbo.tblautoipekonek.ipno,
   dbo.tblautoipekonek.awbno,
   dbo.tblautoipekonek.ipamount,
   dbo.tblautoipekonek.orno,
   dbo.tbladdfunds.username,
   dbo.tbladdfunds.newctfbal,
   dbo.tbladdfunds.addedctfamt,
   dbo.tbladdfunds.oldctfbal,
   dbo.tbladdfunds.newipbal,
   dbo.tbladdfunds.addedipamt,
   dbo.tbladdfunds.oldipbal,
   dbo.tbladdfunds.date,
   dbo.tblautoipekonek.date AS Expr1
FROM   dbo.tblautoipekonek

   LEFT OUTER JOIN dbo.tbladdfunds
                ON dbo.tblautoipekonek.date = dbo.tbladdfunds.date
WHERE  
    ( dbo.tblautoipekonek.date = '06/06/2014' ) 

GROUP BY dbo.tblautoipekonek.ipno,
 dbo.tblautoipekonek.awbno,
 dbo.tblautoipekonek.ipamount,
 dbo.tblautoipekonek.orno,
 dbo.tbladdfunds.username,
 dbo.tbladdfunds.newctfbal,
 dbo.tbladdfunds.addedctfamt,
 dbo.tbladdfunds.oldctfbal,
 dbo.tbladdfunds.newipbal,
 dbo.tbladdfunds.addedipamt,
 dbo.tbladdfunds.oldipbal,
 dbo.tbladdfunds.date,
 dbo.tblautoipekonek.date AS Expr1

答案 2 :(得分:0)

不确定这是否适合您,但我会使用这个:

SELECT
    p.ipno,
    p.awbno,
    p.ipamount,
    p.orno,
    f.username,
    f.newctfbal,
    f.addedctfamt,
    f.oldctfbal,
    f.newipbal,
    f.addedipamt,
    f.oldipbal,
    f.date,
    p.date Expr1
FROM
    dbo.tblautoipekonek p
        CROSS APPLY
            (
                SELECT TOP 1
                    *
                FROM
                    dbo.tbladdfunds f
                WHERE
                    p.date = f.date
                ORDER BY
                    f.newipbal DESC
            ) f

这将从dbo.tblautoipekonek中的每个条目中获取一行,其中dbo.tbladdfunds中的匹配日期条目与newipbal中的值最高