mssql and left join duplicate records

一曲冷凌霜 提交于 2019-12-02 10:11:50

looking to your data could you join must match also for op_code AND instplanheader.op_code = instplan.op_code

$sql = "SELECT DISTINCT
      instplan.debt_code,
      instplan.op_code,
      instplanheader.op_code as plan_op,
      instplan.ipactualpaymentamt
    FROM instplanheader
    LEFT JOIN instplan ON instplanheader.debt_code=instplan.debt_code

        AND instplanheader.op_code = instplan.op_code 

        AND instplan.tran_code NOT IN ('DR3001','DR3002','DR3003','DR3004')
        AND instplan.ipactualpaymentamt > 0.00
        AND instplan.ipactualpaymentdt >= '2019-02-04' AND instplan.ipactualpaymentdt <= '2019-02-04'
          AND instplanheader.iphcreationdate >= '2018-12-01' AND instplanheader.iphcreationdate <= '2019-02-04'
    ";

It means that your right table instplan has multiple rows with the same debt_code.

Let me show what I mean:

DECLARE @TestTable TABLE 
(
    Col1 VARCHAR(10),
    Col2 INT,
    Col3 INT
)    
DECLARE @TestTable2 TABLE 
(
    Col1 VARCHAR(10),
    Col2 VARCHAR(10),
    Col3 VARCHAR(10)
)


INSERT INTO @TestTable
(
    Col1,
    Col2,
    Col3
)
VALUES
 ('A',         10,       20)    
 INSERT INTO @TestTable2
(
    Col1,
    Col2,
    Col3
)
VALUES
   ('A',         'A',       'A')
 , ('A',         'B',       'B')
 , ('A',         'C',       'C')

And query example:

SELECT 
  distinct t1.Col1 t1_Col
, t2.Col1 t2_Col1
, t2.Col2 t2_Col2
, t2.Col3 t2_Col3
FROM @TestTable t1 
LEFT JOIN @TestTable2 t2 ON t2.Col1 = t1.Col1

Nevertheless, we see three rows althought we use DISTINCT keyword.

OUTPUT:

t1_Col  t2_Col1 t2_Col2 t2_Col3
A          A       A       A 
A          A       B       B
A          A       C       C

This seems a touch nonsensical to me:

        AND i.ipactualpaymentdt >= '2019-02-04' 
        AND i.ipactualpaymentdt <= '2019-02-04'
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!