SQL查询显示最近的数量,但按客户分组

时间:2019-02-14 10:54:02

标签: sql oracle greatest-n-per-group

Item Number   |   Customer   |   Creation Date   |   Onhand Qty   
  123               1              03-FEB-19            654
  234               3              03-FEB-19            987
  789               5              03-FEB-19            874
  321               4              03-FEB-19            147
  567               7              03-FEB-19            632
  123               1              29-JAN-19            547
  234               3              29-JAN-19            814
  789               5              29-JAN-19            458
  321               4              29-JAN-19            330
  567               7              29-JAN-19            118

我已经在上面设置了此数据,但是用于数千个项目和数百个客户。

我想做的只是返回最新的“手头数量”字段,所以max(creation_date)取决于项目和客户。

    Item Number   |   Customer   |   Creation Date   |   Onhand Qty   
  123               1              03-FEB-19            654
  234               3              03-FEB-19            987
  789               5              03-FEB-19            874
  321               4              03-FEB-19            147
  567               7              03-FEB-19            632

有效地,我试图按客户和物料查找最近的在手数量,所以我可以说在最近的检查中,“客户1有654个单位的物料123”。

有人可以帮助我吗?

这在Oracle数据库(V11)中。

非常感谢

3 个答案:

答案 0 :(得分:0)

使用row_number()

select * from (select *,row_number() over(partition by Customer order by creation_date desc,qty desc) rn from table
) t where t.rn=1

答案 1 :(得分:0)

使用ROW_NUMBER()如下:

SELECT * FROM (
    SELECT t.*, ROW_NUMBER() OVER(PARTITION BY Customer, Item_Number ORDER BY creation_date DESC) rn
    FROM mytable t
) WHERE rn = 1

在子查询中,ROW_NUMBER()为具有相同客户/项目的记录组中的每个记录分配一个序列号。序列按创建日期降序排列(因此,最高日期排在最前面)。然后,外部查询将对每个组中的第一条记录进行过滤。

DB Fiddle demo 及其示例数据将返回:

ITEM_NUMBER | CUSTOMER | CREATION_DATE | ONHAND_QTY | RN
----------: | -------: | :------------ | ---------: | -:
        123 |        1 | 29-JAN-19     |        547 |  1
        234 |        3 | 29-JAN-19     |        814 |  1
        321 |        4 | 29-JAN-19     |        330 |  1
        789 |        5 | 29-JAN-19     |        458 |  1
        567 |        7 | 29-JAN-19     |        118 |  1

答案 2 :(得分:0)

您可以尝试使用row_number()并在over子句中添加partition by Customer,item order by creation_date desc

select * from 
(
select *,row_number() over(partition by Customer,item order by creation_date desc) rn from table
)A where rn=1
相关问题