本篇對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條件放置的相關講解
以上是sql server求分組最大值,最小值,最大值對應時間,與最小值對應時間的詳細內容。更多資訊請關注PHP中文網其他相關文章!