表:A
编码 水量 抄表时间
001 10 2018-06-15 21:22:50
001 20 2018-06-15 22:22:50
001 25 2018-06-15 21:28:50
002 21 2018-06-15 01:22:50
002 5 2018-06-15 21:28:50
003 10 2018-06-15 11:28:50
查询结果要得到如下:按 抄表时间 ,取最近的那条记录放一起,结果如下
001 20 2018-06-15 22:22:50
002 5 2018-06-15 21:28:50
003 10 2018-06-15 11:28:50
6 个解决方案
#1
最近是怎么规定的?
#2
#3
取最近的那条记录放一起
最近是几个时间之间最近还是离现在时间最近?
最近是几个时间之间最近还是离现在时间最近?
#4
--测试数据
if not object_id(N'Tempdb..#T') is null
drop table #T
Go
Create table #T([编码] nvarchar(23),[水量] int,[抄表时间] nvarchar(39))
Insert #T
select N'001',10,N'2018 06 15 21:22:50' union all
select N'001',20,N'2018 06 15 22:22:50' union all
select N'001',25,N'2018 06 15 21:28:50' union all
select N'002',21,N'2018 06 15 01:22:50' union all
select N'002',5,N'2018 06 15 21:28:50' union all
select N'003',10,N'2018 06 15 11:28:50'
Go
--测试数据结束
SELECT *
FROM
(
SELECT *,
ROW_NUMBER() OVER (PARTITION BY 编码 ORDER BY 抄表时间 DESC) rn
FROM #T
) t
WHERE rn = 1;
#5
SELECT * FROM A_Table AS a,
(SELECT 编码,MAX(抄表时间) AS 抄表时间 FROM A_Table GROUP BY 编码 ) AS b
WHERE a.编码=b.编码 AND a.抄表时间=b.抄表时间
order by a.编码
(SELECT 编码,MAX(抄表时间) AS 抄表时间 FROM A_Table GROUP BY 编码 ) AS b
WHERE a.编码=b.编码 AND a.抄表时间=b.抄表时间
order by a.编码
#6
同问,好问题。
#1
最近是怎么规定的?
#2
#3
取最近的那条记录放一起
最近是几个时间之间最近还是离现在时间最近?
最近是几个时间之间最近还是离现在时间最近?
#4
--测试数据
if not object_id(N'Tempdb..#T') is null
drop table #T
Go
Create table #T([编码] nvarchar(23),[水量] int,[抄表时间] nvarchar(39))
Insert #T
select N'001',10,N'2018 06 15 21:22:50' union all
select N'001',20,N'2018 06 15 22:22:50' union all
select N'001',25,N'2018 06 15 21:28:50' union all
select N'002',21,N'2018 06 15 01:22:50' union all
select N'002',5,N'2018 06 15 21:28:50' union all
select N'003',10,N'2018 06 15 11:28:50'
Go
--测试数据结束
SELECT *
FROM
(
SELECT *,
ROW_NUMBER() OVER (PARTITION BY 编码 ORDER BY 抄表时间 DESC) rn
FROM #T
) t
WHERE rn = 1;
#5
SELECT * FROM A_Table AS a,
(SELECT 编码,MAX(抄表时间) AS 抄表时间 FROM A_Table GROUP BY 编码 ) AS b
WHERE a.编码=b.编码 AND a.抄表时间=b.抄表时间
order by a.编码
(SELECT 编码,MAX(抄表时间) AS 抄表时间 FROM A_Table GROUP BY 编码 ) AS b
WHERE a.编码=b.编码 AND a.抄表时间=b.抄表时间
order by a.编码
#6
同问,好问题。