SQL获取第一条记录的方法(sqlserver、oracle、mysql数据库)
作者:mrr 时间:2024-01-23 00:15:03
Sqlserver 获取每组中的第一条记录
在日常生活方面,我们经常需要记录一些操作,类似于日志的操作,最后的记录才是有效数据,而且可能它们属于不同的方面、功能下面,从数据库的术语来说,就是查找出每组中的一条数据。下面我们要实现的就是在sqlserver中实现从每组中取出第一条数据。
例子
我们要从上面获得的有效数据为:
对应的sql语句如下所示:
select * from t1 t where id = (select top 1 id from t1 where grp = t.grp order by createtime desc )
下面给大家介绍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.
mysql 中只获取1条数据
SELECT * FROM 表 LIMIT 0, 10
LIMIT 接受一个或两个数字参数。
参数必须是一个整数常量。
如果给定两个参数,第一个参数指定第一个返回记录行的偏移量,
第二个参数指定返回记录行的最大数目。
初始记录行的偏移量是 0(而不是 1)
主意:limit 用于 having 之后
自己的示例:
select count(1),tpc_equipment_code from tb_parts_consume GROUP BY tpc_equipment_code ORDER BY count(1) DESC LIMIT 1;
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python用pickle模块实现“增删改查”的简易功能
GO语言基本数据类型总结
六个实用Pandas数据处理代码
Python二分查找+字符串模板+textwrap模块,
![](https://img.aspxhome.com/file/2023/4/112444_0s.webp)
Python matplotlib学习笔记之坐标轴范围
![](https://img.aspxhome.com/file/2023/8/88038_0s.jpg)
详解Go语言中new和make关键字的区别
python 实现快速生成连续、随机字母列表
MySQL基础教程第一篇 mysql5.7.18安装和连接教程
![](https://img.aspxhome.com/file/2023/5/112325_0s.jpg)
20个解决日常编程问题的Python代码分享
![](https://img.aspxhome.com/file/2023/8/89118_0s.png)
python创建与遍历List二维列表的方法
python 根据网易云歌曲的ID 直接下载歌曲的实例
![](https://img.aspxhome.com/file/2023/5/101205_0s.jpg)
ajax取消挂起请求的处理方法
利用索引提高SQL Server数据处理的效率
python 3.7.0 安装配置方法图文教程
![](https://img.aspxhome.com/file/2023/2/65522_0s.jpg)
asp如何从数据库中删除废旧的电子信箱地址?
eWebEditor不支持IE8/IE7的解决方法
![](https://img.aspxhome.com/file/UploadPic/20102/28/4270100787_166776e513_o-72s.jpg)
全屏flash的尺寸分析
![](https://img.aspxhome.com/file/UploadPic/20092/11/01-11s.jpg)
打包发布Python模块的方法详解
如何利用python turtle绘图自定义画布背景颜色
![](https://img.aspxhome.com/file/2023/4/97414_0s.png)
教你怎么用python selenium实现自动化测试
![](https://img.aspxhome.com/file/2023/2/93962_0s.png)