SQL conundrum, how to select latest date for part, but only 1 row per part (unique)

前端 未结 3 413
面向向阳花
面向向阳花 2021-01-13 04:47

I am trying to wrap my head around this one this morning.

I am trying to show inventory status for parts (for our products) and this query only becomes

相关标签:
3条回答
  • 2021-01-13 04:55
      SELECT *
      FROM   (SELECT i.*,
          ROW_NUMBER() OVER(PARTITION BY ldPart ORDER BY ldDate DESC) r
          FROM   inventoryReport i
          WHERE  ldPart in ('ABC123', 'BFD21', 'AA123', etc)
             )
      WHERE  r = 1
    
    0 讨论(0)
  • 2021-01-13 05:08

    EDIT: Be sure to test the performance of each solution. As pointed out in this question, the CTE method may outperform using ROW_NUMBER.

    ;with cteMaxDate as (
        select ldPart, max(ldDate) as MaxDate
            from inventoryReport
            group by ldPart
    )
    SELECT md.MaxDate, ir.ptProdLine, ir.inPart, ir.inSite, ir.inAbc, ir.ptUm, ir.inQtyOh + ir.inQtyNonet AS in_qty_oh, ir.inQtyAvail, ir.inQtyNonet, ir.ldCustConsignQty, ir.inSuppConsignQty
        FROM cteMaxDate md
            INNER JOIN inventoryReport ir
                on md.ldPart = ir.ldPart
                    and md.MaxDate = ir.ldDate
    
    0 讨论(0)
  • 2021-01-13 05:16

    You need to join into a Sub-query:

    SELECT i.ldPart, x.LastDate, i.inAbc
    FROM inventoryReport i
    INNER JOIN (Select ldPart, Max(ldDate) As LastDate FROM inventoryReport GROUP BY ldPart) x
    on i.ldPart = x.ldPart and i.ldDate = x.LastDate
    
    0 讨论(0)
提交回复
热议问题