sql 分组后获取其中一个字段最大值的整条记录

作者:袖梨 2022-06-29

mysql的语句:

 代码如下 复制代码

SELECT  *

FROM (SELECT * FROM testTable ORDER BY createDate desc) pcc

GROUP BY name

Mysql中在分组前先排好序就可以找到需要的记录了,返回的就是按照name分组后不重复的符合条件的第一条记录。

在sqlserver中有很好的解决办法,

 代码如下 复制代码

select * from (

select id,name,counts,createDate,row_number() over(partition by name order by createDate desc) rn

from testTable

) t where t.rn <=1

sqlserver 会有一点不错下面我看看

----------------------------------------------
--有id,name,createDate的一张表testTable
--根据name分组,获取每组中createDate最大的那条记录(整条)查询出来
----------------------------------------------

创建一张表,语句如下:

 代码如下 复制代码

CREATE TABLE [dbo].[testTable]
(
[id] [int] NOT NULL IDENTITY(1, 1),
[name] [nchar] (10) COLLATE Chinese_PRC_CI_AS NULL,
[counts] [int] NULL,
[createDate] [datetime] NULL
)
GO
-- Constraints and Indexes
ALTER TABLE [dbo].[testTable] ADD CONSTRAINT [PK_testTable] PRIMARY KEY CLUSTERED ([id])
GO

插入测试数据:

 代码如下 复制代码

insert into testTable(id,name,counts,createDate) values(1,'A         ',20,'01 14 2011 10:52PM')
insert into testTable(id,name,counts,createDate) values(2,'A         ',10,'02 14 2011 10:52PM')
insert into testTable(id,name,counts,createDate) values(3,'B         ',20,'03 14 2011 10:52PM')
insert into testTable(id,name,counts,createDate) values(4,'B         ',40,'04 14 2011 10:52PM')
insert into testTable(id,name,counts,createDate) values(5,'B         ',10,'05 14 2011 10:52PM')
insert into testTable(id,name,counts,createDate) values(6,'C         ',20,'06 14 2011 10:52PM')
insert into testTable(id,name,counts,createDate) values(7,'C         ',40,'07 14 2011 10:52PM')

sql语句

select * from (
 select id,name,counts,createDate,row_number() over(partition by name order by createDate desc) rn
 from testTable
) t where t.rn <=1

相关文章

精彩推荐