本篇对sql server求分组最大值,最小值,最大值对应时间,和最小值对应时间的相关知识做出了讲解。
先创建Students表
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求分组最大值,最小值,最大值对应时间,和最小值对应时间做出了讲解,更多的学习资料清关注php中文网即可观看。
相关推荐:
关于left join on 和where条件放置的相关讲解
Atas ialah kandungan terperinci sql server求分组最大值,最小值,最大值对应时间,和最小值对应时间. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!