sql server求分组最大值,最小值,最大值对应时间,和最小值对应时间

先创建数据库

CREATE TABLE [dbo].[Students](
[Id] [int] IDENTITY(1,1) NOT NULL,
[age] [int] NULL,
[name] [nvarchar](50) NULL,
[addTime] [datetime]  NULL
) ON [PRIMARY]

插入几条测试数据

INSERT [dbo].[Students] ([age], [name], [addTime]) VALUES (22, N'李四', '2015-04-08 01:00:00.000')
INSERT [dbo].[Students] ([age], [name], [addTime]) VALUES (8, N'李四', '2017-05-03 00:00:00.000')
INSERT [dbo].[Students] ([age], [name], [addTime]) VALUES (98, N'李四', '2017-10-03 00:00:00.000')
INSERT [dbo].[Students] ([age], [name], [addTime]) VALUES (34, N'张三', '2016-09-08 00:00:00.000')
INSERT [dbo].[Students] ([age], [name], [addTime]) VALUES (45, N'张三','2011-05-08 00:00:00.000')
INSERT [dbo].[Students] ( [age], [name], [addTime]) VALUES (5, N'张三', '2014-04-01 00:00:00.000')

第一种写法:

  这种写法用到了窗口函数,窗口函数的行为描述出现在函数的OVER子句中,并涉及多个元素,3个核心元素分别是:分区,排序和框架

select distinct name,
maxAge, max(case maxAgenum when 1 then addtime else '' end) over(partition by name) maxAddTime ,
minage,max(case minAgenum when 1 then addtime else '' end) over(partition by name) minAddTime
from (
select name,addtime,
max(age) over(partition by name) maxAge,
min(age) over(partition by name) minAge,
RANK() over(partition by name order by age desc) maxAgeNum ,
RANK() over(partition by name order by age ) minAgeNum from students
) s

第二种写法:

with s as
(
select name,max(age) maxAge,min(age) minAge from students
group by name
)
select name,max(maxAge) maxAge,max(maxAgeTime) maxAgeTime,max(minAge) minAge,max(minAgeTime) minAgeTime from (
select ss.name,s.maxAge,ss.addTime maxAgeTime,0 minAge, '' minAgeTime from students ss inner join s on ss.name=s.name and ss.age=s.maxAge
union all
select ss.name,0 maxAge , '' maxAgeTime,s.minAge minAge,ss.addTime minAgeTime from students ss inner join s on ss.name=s.name and ss.age=s.minAge
) a group by name

结果如下图:

sql server求分组最大值,最小值,最大值对应时间,和最小值对应时间

sql server求分组最大值,最小值,最大值对应时间,和最小值对应时间

上一篇:Windows资源监视器软件的原理


下一篇:16.用pycharm导入自己写的模块时,import无法识别的解决办法