排序后取第一条记录 select * from (select * from table order by a )C where rownum=1
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.
===================================================================================
对多数据进行分组排序后取每组第一条记录
- SELECT *
- FROM (SELECT ROW_NUMBER() OVER(PARTITION BY <PK_FINANCE_ACCOUNT_1> ORDER BY <amassdate> DESC) LEV,
- <hx_amass_liquid>.*
- FROM <hx_amass_liquid>)
- WHERE LEV = 1
- ORDER BY <PK_FINANCE_ACCOUNT_2> DESC
<PK_FINANCE_ACCOUNT_1> -- 分组列
<amassdate> -- 排序列
<hx_amass_liquid> -- 表名
<PK_FINANCE_ACCOUNT_2> -- 排序列
注:<hx_amass_liquid>.* -- 一定要有表名,否则会报“缺失表达式”错误
==========================================================
分组时不仅想取每组的第一条记录,还想取每组共有几条记录
SELECT *
FROM (
SELECT ROW_NUMBER() OVER(PARTITION BY PK_FINANCE_ACCOUNT ORDER BY amassdate DESC) LEV,
count(0) over(partition by PK_FINANCE_ACCOUNT) cnt,
hx_amass_liquid.*
FROM
hx_amass_liquid
)
WHERE LEV = 1
ORDER BY PK_FINANCE_ACCOUNT DESC