SQL Server查询分组结果中第一条记录的方法
2016-03-02 15:24
309 查看
select * from
(
select mp.MsgID,m.Content,m.CreatorID,m.CreateTime,ROW_NUMBER() over(partition by m.CreatorID order by m.CreateTime desc) as new_index
from U_Account_WX_MsgProperty mp
join U_Account_WX_Messages m on mp.MsgID=m.MsgID
where mp.UserID=453 and mp.IsRead=0 and mp.IsDelete=0
and m.CreateTime between '2016-01-01' and '2016-03-30'
) result
where result.new_index=1
注意partition后面跟着的是分组字段,也就是根据CreatorID分组
ROW_NUMBER() over(partition by m.CreatorID order by m.CreateTime desc)这行语句的意思是根据CreatorID分组并且按照CreateTime倒序排序,给查询好的每个组中的数据都编上行号
(
select mp.MsgID,m.Content,m.CreatorID,m.CreateTime,ROW_NUMBER() over(partition by m.CreatorID order by m.CreateTime desc) as new_index
from U_Account_WX_MsgProperty mp
join U_Account_WX_Messages m on mp.MsgID=m.MsgID
where mp.UserID=453 and mp.IsRead=0 and mp.IsDelete=0
and m.CreateTime between '2016-01-01' and '2016-03-30'
) result
where result.new_index=1
注意partition后面跟着的是分组字段,也就是根据CreatorID分组
ROW_NUMBER() over(partition by m.CreatorID order by m.CreateTime desc)这行语句的意思是根据CreatorID分组并且按照CreateTime倒序排序,给查询好的每个组中的数据都编上行号
相关文章推荐
- oracle 手动创建job语句
- mongodb命令行操作
- 无法打开物理文件xxx.mdf操作系统错误 5:“5(拒绝访问。)” (Microsoft SQL Server,错误: 5120)的解决方法
- Logstash+Redis+Elasticsearch+Kibana+Nginx搭建日志分析系统
- JDBC连接各种数据库
- gedis——go语言开发的redis代理
- mysql将字符转换成数字
- SQL表连接查询inner join left join right join full join ...
- ORACLE ADF:项目搭建
- 数据库索引-扫盲
- pdm和sql双向操作
- 性能优化之数据库优化
- 应该在VMware平台还是物理机平台上运行Oracle RAC?
- mysql多表查询
- oracle12c卸载过程
- SQL SERVER 统计SQL语句或存储过程执行时间
- SQL数据库 更改数据类型
- Oracle中group by用法
- SQL2008 的收缩日志&log日志丢失恢复
- 一次 MySQL 索引优化的经历