按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.
解析函數的最後一組操作中執行一個查詢,除了最後的ORDER BY子句。所有串連和地方、GROUP BY和之前有條款完成分析處理功能。因此,解析函數只能出現在挑選清單中或ORDER BY子句。
文法結構:
analytic_function ([ arguments ]) OVER (analytic_clause)
其中analytic_clause結構包括:
[ query_partition_clause ][ order_by_clause [ windowing_clause ] ]
也就是:函數名( [ 參數 ] ) over( [ 分區子句 ] [ 排序子句 [ 滑動視窗子句 ] ])
這裡PARTITION BY 引導的分區子句類似於聚組函數中的group by,排序子句可看成是select語句中的order by.