簡體   English   中英

如何從組中獲取第一個非零行?

[英]How to get 1st non-zero row from a group?

我的桌子看起來像這樣。 表的名稱為 table1

column1    column2   column3
  a           0       date1
  a           0       date2
  a           4       date3
  a           7       date4
  b           0       date1 
  b           6       date2
  b           0       date3
  b           4       date4
  c           2       date1
  c           1       date2
  c           5       date3
  c           9       date4
  d           0       date1
  d           0       date2
  d           8       date3
  d           0       date4

我想要我的 output 作為

column1        column2
   a              4
   b              6
   c              2
   d              8

從上表中,您可能已經注意到我對對 column1 進行分組並從 column2 中獲取第一個非零數字感興趣。 任何幫助將不勝感激。 謝謝

您可以使用not exists的查詢:

select *
from t
where column2 <> 0 and not exists (
    select *
    from t as x
    where x.column1 = t.column1
    and   x.column2 <> 0
    and   x.column3 < t.column3
)

使用子查詢:

select t2.column1, t2.column2
from  (select column1, min(column3) as column3
       from t
       where column2 > 0) t1
join t t2 on (t1.column1 = t2.column1 and t1.min_column3 = t2.column3);

t1子查詢選擇包含第一個非零值的日期, t2查詢獲取實際的column2值。

你好oracle中的其他解決方案

     select * from (
select  a.* 
, case when column2 <> 0 then row_number()over(partition by column1 , case when column2 <>0 then 1 else 0 end order by (select 1 from dual)) end as rn 
from yourtable a) where rn=1; 
 

暫無
暫無

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

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