mssql and left join duplicate records

前端 未结 3 961
长情又很酷
长情又很酷 2021-01-28 23:03

Original Query

SELECT DISTINCT
      IP.op_code as ip_op_code,
      IPH.op_code as iph_op_code,
      debt_trans.tx_amount as cash,
      DT.tx_amount as revenu         


        
相关标签:
3条回答
  • 2021-01-28 23:29

    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'
        ";
    
    0 讨论(0)
  • 2021-01-28 23:33

    This seems a touch nonsensical to me:

            AND i.ipactualpaymentdt >= '2019-02-04' 
            AND i.ipactualpaymentdt <= '2019-02-04'
    
    0 讨论(0)
  • 2021-01-28 23:37

    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
    
    0 讨论(0)
提交回复
热议问题