簡體   English   中英

SQL 根據其他行值排除行

[英]SQL Exclude row based on other rows value

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                             
                                                

我想在“行發票列”中有任何其他數字時刪除“-1”行。 這是特定於每個 Source_PMT_ID 的。 如果沒有'1'行返回-1。 如何在我的 sql 查詢中捕獲這個?

懷疑你想要 window 功能:

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

子查詢中的 window max()檢查是否至少存在一行具有相同的source_pmt_idline_invoice值而不是-1 外部查詢使用該信息過濾掉line_invoice值為-1的行,同時保留那些對於同一source_pmt_id沒有其他值的行。

假設 -1 是最小的數字,並且 line_invoice 從那里上升:

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 

這個 Fiddle 展示了它是如何工作的。

window 功能的一種方法:

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;

或者,沒有子查詢:

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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM