简体   繁体   中英

Looking for a way to filter the result of these UNION queries in SQL

I would like to filter the result of these 2 queries, connected by UNION. I think of adding a SELECT statement to filter the latest in terms of date, ID and name. The issue is that these 2 queries produce a duplicate after using UNION, which I have to avoid. Only need one latest date, name and ID.

(select  authorize_id,
purchase_authorizer_api.Get_Name(authorize_id) as "Authorizer Name",  
max(date_approved) as "Last Date Approved", 'PR' as "Approval Type"
from PURCH_REQ_LINE_APPROVAL
group by authorize_id )

union 

( select  authorize_id,
purchase_authorizer_api.get_name(authorize_id) as "Authorizer Name",
 max(date_approved) as "Last Date Approved", 'PO' as "Approval Type"
from PURCHASE_ORDER_APPROVAL
group by authorize_id ) 

Here is some sample data from the 2 queries:

AUTHORIZE_ID    Authorizer Name     Last Date Approved  Approval Type
AANDR           Alfredo And         2012-10-16 12:51           PR
AANDR           Alfredo And         2016-09-06 13:08           PO
AESFAH          Arash Esf           2017-05-26 13:28           PO
AHAMM           Ahmed Hamd          2019-12-04 14:15           PO
AJAHAN          Al Jaha             2012-11-02 9:56            PR
AJAHAN          Al Jaha             2013-10-29 14:17           PO

I would like to get only the latest date from these, so it will avoid duplicates.
Any help would be greatly appreciated. Thanks.

Use ROW_NUMBER() window function on the UNION of the 2 tables to return 1 row for each authorize_id :

with cte as (
  select authorize_id, date_approved, 'PR' as "Approval Type" from PURCH_REQ_LINE_APPROVAL  
  union all
  select authorize_id, date_approved, 'PO' as "Approval Type" from PURCHASE_ORDER_APPROVAL 
)
select 
  t.authorize_id, 
  purchase_authorizer_api.Get_Name(t.authorize_id) as "Authorizer Name", 
  t.date_approved as "Last Date Approved", 
  t."Approval Type" 
from (
  select c.*, row_number() over (partition by c.authorize_id order by c.date_approved desc) rn
  from cte c
) t
where t.rn = 1

See a simplified demo (without Authorizer Name ).
Results:

| authorize_id | Authorizer Name | Last Date Approved       | Approval Type |
| ------------ | --------------- | ------------------------ | ------------- |
| AANDR        |                 | 2016-09-06T13:08:00.000Z | PO            |
| AESFAH       |                 | 2017-05-26T13:28:00.000Z | PO            |
| AHAMM        |                 | 2019-12-04T14:15:00.000Z | PO            |
| AJAHAN       |                 | 2013-10-29T14:17:00.000Z | PO            |

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM