Oracle数据库查询 - 有关加入和仅返回最新日期的多个问题

时间:2017-03-30 12:57:51

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

我有2个表,库存和交易 在库存中我有列Part_id,Location_Id和Zone_id(所有VARCHAR) 在事务中,我有列Part_id,代码和日期(Part_ID和代码是VARCHAR,日期是TIMESTAMP与本地时区)

我想查看Inventory表格中的所有Part_id,Location_id和Zone_Id以及一个可以返回Code' Pick'的最新日期的列。对于事务表中的Part_Id(如果存在),如果不存在,则返回该Part_ID的空白。 问题是Tranasactions可以将Inventory中的Part_Id与其他代码匹配。所以只去库存.part_id = transactions.part_id将无效。 当没有带有代码Pick的Part_id的记录时,如何返回...

Inventory:                       Transactions:

│Part_ID│Location_ID│Zone_ID│    │Part_ID│Code   │Date
│a001   │A          │Z      │    │a001   │Pick   │01/01/2017│
│b002   │B          │X      │    │b002   │Check  │01/02/2017│
│c003   │C          │Y      │    │c003   │Receive│05/02/2017│
│d004   │D          │Q      │    │d004   │Pick   │09/02/2017│
                                 │a001   │Pick   │11/02/2017│

Wanted result:

│Part_ID│Location_ID│Zone_ID│LatestDateofPick│
│a001   │A          │Z      │11/02/2017      │
│b002   │B          │X      │                │
│c003   │C          │Y      │                │
│d004   │D          │Q      │09/02/2017      │

我只是一个SQL的初学者,所以我对此有点赞成,请怜悯。 :) 谢谢你帮我解决了这个问题!

2 个答案:

答案 0 :(得分:0)

你需要这样的东西来获得你的目标

select t.Part_ID,
    i.Location_ID,
    i.Zone_ID,
    case when t.Code <> 'Pick' then null else max(t.Date) end as LatestDateOfPick
from Transactions t
join Inventory  i on t.Part_ID = i.Part_ID
group by t.Part_ID,i.Location_ID,i.Zone_ID,t.Code

只有当代码&#34;选择&#34;时才会提取max日期。否则会留下NULL

答案 1 :(得分:0)

我使用外部联接和日期的最大值

来看到这一点
  -- Start test data
  with inventory (part_id, location_id, zone_id) as
       (select 'a001','A','Z' from dual union all
        select 'b002','B','X' from dual union all
        select 'c003','C','Y' from dual union all
        select 'd004','D','Q' from dual),
       transaction (part_id, code, txn_date) as 
       (select 'a001','Pick',to_date( '01-jan-17','DD-MON-RR') from dual union all
        select 'b002','Check',to_date( '02-JAN-17','DD-MON-RR') from dual union all
        select 'c003','Receive',to_date( '02-may-17','DD-MON-RR') from dual union all
        select 'd004','Pick',to_date( '02-sep-17','DD-MON-RR') from dual union all
        select 'a001','Pick',to_date( '02-nov-17','DD-MON-RR') from dual)
  -- end test data      
select inv.part_id,
       inv.location_id,
       inv.zone_id,
       MAX(txn.txn_date)
from inventory inv
     left outer join transaction txn on (inv.part_id = txn.part_id AND txn.code = 'Pick')
group by inv.part_id, inv.location_id, inv.zone_id;


"PART_ID"             "LOCATION_ID"         "ZONE_ID"     MAX(TXN.TXN_DATE)"           
"d004"                "D"                   "Q"           "09/02/2017 00:00:00"         
"c003"                "C"                   "Y"           ""                            
"a001"                "A"                   "Z"           "11/02/2017 00:00:00"         
"b002"                "B"                   "X"           ""