Oracle-仅返回每个产品的第一行

时间:2020-01-08 14:43:50

标签: sql oracle

在第一个SELECT语句中,该报告获取具有装运活动的所有产品的inv详细信息。然后,有一个UNION连接另一个SELECT语句,以获取上一个日历年无活动的产品。

但是,第二条SELECT语句中返回的记录具有多个header_id,因此具有多行…而不是像第一条SELECT语句那样具有单行。您是否知道如何仅在第二条SELECT语句中提取每个记录的第一个header_id?

下面的代码和示例结果集。在数据中,产品#7应该只列出header_id 1372288的行,它是输入到数据库中的最后一个ID。

enter image description here

select 3 sort_key, header_Id,location_id,nlasinv.product,
                                   start_inv,produced produced_inv,stored,from_stock,shipped,
                                   (start_inv + produced + stored) - (from_stock + shipped) end_inv,nlas_ops_mtd_prodsize(111,nlasinv.product,'31-DEC-19'), nlas_ops_mtd_shipsize(111,nlasinv.product,'31-DEC-19'),nlas_ops_ytd_prodsize(111,nlasinv.product,'31-DEC-19'), nlas_ops_ytd_shipsize(111,nlasinv.product,'31-DEC-19')
                                   from nlas_header inv,
                                     nlas_inventory nlasinv
                                   where nlasinv.header_id = 1372168   
                                   and inv.id = nlasinv.header_id
    union 
    select distinct
       3 sort_key,header_Id,location_id,nlasinv.product,
       start_inv,produced produced_inv,stored,from_stock,shipped,
                                   (start_inv + produced + stored) - (from_stock + shipped) end_inv,nlas_ops_mtd_prodsize(111,nlasinv.product,'31-DEC-19'),
       nlas_ops_mtd_shipsize(111,nlasinv.product,'31-DEC-19'),nlas_ops_ytd_prodsize(111,nlasinv.product,'31-DEC-19'),
       nlas_ops_ytd_shipsize(111,nlasinv.product,'31-DEC-19')
       from
         nlas_inventory nlasinv,
         nlas_header hdr
         where
         nlasinv.header_id = hdr.id
         and hdr.location_id = 409
         and hdr.observation_date >= trunc(to_date('31-DEC-19','dd-mon-rr'),'year') 
         and nlasinv.product not in
         (select distinct product from
           nlas_header h,
           nlas_inventory i
           where i.header_id = 1372168) 
order by product, header_id des

c

2 个答案:

答案 0 :(得分:2)

我不知道您的查询与显示的“表”数据有什么关系。但是您似乎想要row_number()

select t.*
from (select t.*, row_number() over (partition by product order by header_id desc) as seqnum
      from t
     ) t
where seqnum = 1;

如果该查询用于生成数据,则将其包装在CTE中。

答案 1 :(得分:1)

这也可以通过在where子句中添加自联接来实现

and hdr.header_id = (
   select max(hdr2.header_id) 
   from nlas_header hdr2 
   where hdr2.location_id = hdr.location_id 
   and hdr2.product_id = hdr.product_id)