oracle查詢:取出每組中的第一條記錄

來源:互聯網
上載者:User

oracle查詢:取出每組中的第一條記錄
按type欄位分組,code排序,取出每組中的第一條記錄

 

方法一:

 

select type,min(code) from group_info 
group by type;

 

注意:select 後面的列要在group by 子句中,或是用彙總函式包含,否則會有語法錯誤。

 

方法二:

 

SELECT * FROM(
SELECT z.type , z.code ,ROW_NUMBER()
OVER(PARTITION BY z.type ORDER BY z.code) AS code_id
FROM group_info z
)
WHERE code_id =1;

 

這裡涉及到的over()是oracle的分析函數

 

參考sql reference文檔:

 

Analytic functions compute an aggregate value based on a group of rows. They differ from aggregate functions in that they return multiple rows for each group.

 

Analytic functions are the last set of operations performed in a query except for the final ORDER BY clause.
All joins and all WHERE , GROUP BY ,
and HAVING clauses are completed before the analytic functions are processed. Therefore, analytic functions can appear only in the select list or ORDER BY clause.

 

文法結構:

 

analytic_function ([ arguments ]) OVER (analytic_clause)

其中analytic_clause結構包括:

 

[ query_partition_clause ][ order_by_clause [ windowing_clause ] ]

 

也就是:函數名( [ 參數 ] ) over( [ 分區子句 ]  [ 排序子句 [ 滑動視窗子句 ] ])

 

     這裡PARTITION BY 引導的分區子句類似於聚組函數中的group by,排序子句可看成是select語句中的order by.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.