LINE_INVOICE PAYMENT_SOURCE SOURCE_PMT_ID
-1 Payment Received 7369442
1 Payment Received 7369442
2 Payment Received 7369442
3 Payment Received 7369442
4 Payment Received 7369442
5 Payment Received 7369442
6 Payment Received 7369442
7 Payment Received 7369442
8 Payment Received 7369442
9 Payment Received 7369442
10 Payment Received 7369442
11 Payment Received 7369442
12 Payment Received 7369442
I would like to remove the '-1' row anytime there is in any other number in the 'Line invoice column'. This is specfic for each Source_PMT_ID. If there is no '1' row return -1. How can I capture this in my sql query?
I suspect that you want window functions:
select *
from (
select
t.*,
max(case when line_invoice <> -1 then 1 else 0 end)
over(partition by source_pmt_id) flag
from mytable t
) t
where line_invoice <> -1 or flag = 0
The window max()
in the subquery checks if at least one row exists with the same source_pmt_id
and a line_invoice
value other than -1
. The outer query uses that information to filter out rows where line_invoice
has value -1
, while retaining those that have no other value for the same source_pmt_id
.
Assuming -1 is the lowest number and that line_invoice goes up from there:
select *
from table1 tab
where LINE_INVOICE >= case when (select max(line_invoice)
from table1 tb_
where tb_.payment_source = tab.payment_source
and tb_.source_pmt_id = tab.source_pmt_id) = -1 then -1 else 0 end
One way with window functions:
select t.*
from (select t.*, max(line_invoice) over (partition by SOURCE_PMT_ID) as max_line_invoice
from t
) t
where line_invoice > -1 or max_line_invoice = -1;
Or, without a subquery:
select t.*
from t
order by row_number() over (partition by source_pmt_id
order by case when line_invoice <> -1 then 1 else 2 end
)
fetch first 1 row with ties;
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.