DB2 Query获取最新数据

时间:2018-04-16 19:03:53

标签: sql group-by db2 max

我需要查询DB2表以获取每个唯一的Sup_Num和CONTAINER_CODE组合存储在表中的最新数据。我遇到的问题是我无法弄清楚如何只获取最近日期的数据(INSERTED_DT)。我尝试在INSERTED_DT字段上使用Max()函数,但它给了我完全相同的结果,而不使用Max()函数。当我搜索Max()函数用法示例时,我没有看到这样的内容,所以我希望有人可以提供帮助。

我使用的查询是:

Select Distinct
    SupLookup.SUPPLIER_NO concat SupLookup.SUPPLIER_LOCATION AS Sup_Num,
    SupLookup.CONTAINER_CODE,
    AllocationType.ALLOC_TYPE_DESC,
    Allocation.ALLOC_QTY,
    Allocation.SAFE_STOCK_QTY,
    Allocation.ALLOC_QTY + Allocation.SAFE_STOCK_QTY AS CALC_TOT_ALLOC_REQ_QTY,
    SupLookup.ALLOC_REQ_QTY,
    SupLookup.TOT_ALLOC_REQ_QTY,
    SupLookup.DISC_QTY,
    SupLookup.FILL_PERCENT,
    MAX(SupLookup.INSERTED_DT) as Insert_DT

From RCX.RXSAL1 Allocation
    Inner Join rcx.RXALT1 AllocationType on Allocation.ALLOC_TYPE_ID = AllocationType.ALLOC_TYPE_ID
    Left Join rcx.RXPIR1 SupLookup on Allocation.SUPPLIER_ID = SupLookup.SUPPLIER_ID And allocation.CONTAINER_TYPE_ID = SupLookup.CONTAINER_TYPE_ID

Where Allocation.PLANT_ID= '50000036'

Group by 
    SupLookup.SUPPLIER_NO concat SupLookup.SUPPLIER_LOCATION,
    SupLookup.CONTAINER_CODE,
    AllocationType.ALLOC_TYPE_DESC,
    Allocation.ALLOC_QTY,
    Allocation.SAFE_STOCK_QTY,
    Allocation.ALLOC_QTY + Allocation.SAFE_STOCK_QTY,
    SupLookup.ALLOC_REQ_QTY,
    SupLookup.TOT_ALLOC_REQ_QTY,
    SupLookup.DISC_QTY,
    SupLookup.FILL_PERCENT

ORDER BY Sup_Num ASC

我得到的是这样的:

Bad Data

但我想要的是它为Sup_Num和Container_Code的每个组合选择最近的日期,如下所示:

Good Data

- 编辑 -

在此实例中,简单的max / group by子查询here失败(服务器超时)。有人在某一时刻暗示了这一点,但后来删除了帖子。

1 个答案:

答案 0 :(得分:1)

您的查询不起作用,因为FILL_PERCENT不那么独特,为每一行组成一个单独的组。 除了scaisEdge提到的子查询之外,您还可以使用ROW_UMBER函数 - 按INSERTED_DT降序排序,只检索每个SupLookup.SUPPLIER_NO,SupLookup.CONTAINER_CODE组合的第一行。

这看起来像这样:

with temp as (
    Select 
        SupLookup.SUPPLIER_NO concat SupLookup.SUPPLIER_LOCATION AS Sup_Num,
        SupLookup.CONTAINER_CODE,
        AllocationType.ALLOC_TYPE_DESC,
        Allocation.ALLOC_QTY,
        Allocation.SAFE_STOCK_QTY,
        Allocation.ALLOC_QTY + Allocation.SAFE_STOCK_QTY AS CALC_TOT_ALLOC_REQ_QTY,
        SupLookup.ALLOC_REQ_QTY,
        SupLookup.TOT_ALLOC_REQ_QTY,
        SupLookup.DISC_QTY,
        SupLookup.FILL_PERCENT,
        SupLookup.INSERTED_DT,
        row_number() over (partition by SupLookup.SUPPLIER_NO, SupLookup.CONTAINER_CODE order by SupLookup.INSERTED_DT desc) as rownum

    From RCX.RXSAL1 Allocation
        Inner Join rcx.RXALT1 AllocationType on Allocation.ALLOC_TYPE_ID = AllocationType.ALLOC_TYPE_ID
        Left Join rcx.RXPIR1 SupLookup on Allocation.SUPPLIER_ID = SupLookup.SUPPLIER_ID And allocation.CONTAINER_TYPE_ID = SupLookup.CONTAINER_TYPE_ID

    Where Allocation.PLANT_ID= '50000036'
) 
SELECT Sup_Num, CONTAINER_CODE, ALLOC_TYPE_DESC, ALLOC_QTY, SAFE_STOCK_QTY, CALC_TOT_ALLOC_REQ_QTY, ALLOC_REQ_QTY, TOT_ALLOC_REQ_QTY, DISC_QTY, FILL_PERCENT,INSERTED_DT
  FROM temp
WHERE rownum = 1