oracle查詢:取出每組中的第一條記錄
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.