我有一个看起来像这样的表: (使用Sql-server 2012)
ID------------DAY----------HOUR--COMMENT
00050064 | 2015-09-30 | 14:41 | Creaci¢n de Pedido UD3503-0000001 ==> UD4003
00050064 | 2015-09-30 | 11:52 | Se di¢ de alta el documento: UD4003-0000003
00050064 | 2015-09-30 | 11:42 | Asignaci¢n de t‚cnico: MANUEL REGALADO
00050064 | 2015-09-30 | 11:42 | Cambio de fecha y hora programa
00050064 | 2015-09-30 | 11:40 | SE PROGRAMARA POSTERIOR MENTE
00050064 | 2015-09-30 | 11:39 | PRUEBA NUMERO SERIE OS ANALISIS
我设法按日期和时间排序结果,我可以看到最后一条评论,但问题是,由于我的ID不是唯一的,我不知道如何选择最新的评论。
我的疑问:
select * from
(
select gdoshistorial.c1 as ID,max(gdoshistorial.c3) as [DAY],
max(gdoshistorial.c4) as [TIME], gdoshistorial.c6 AS COMMENT from gdos
left join gdoshistorial on GDOSHISTORIAL.c1 = gdos.c1
where gdos.c1 = gdoshistorial.c1 and gdoshistorial.c1 = '00050064'
group by GDOSHISTORIAL.c1,GDOSHISTORIAL.c6
)v
order by [ID],[DAY],[TIME] desc
请帮我找到一种方法来选择第一行并忽略重复的id's 期望的结果示例:
ID------------DAY----------HOUR--COMMENT
00050064 | 2015-09-30 | 14:41 | Creaci¢n de Pedido UD3503-0000001 ==> UD4003
而不是从同一个ID中获取大量评论,我只想查看最新的评论。
答案 0 :(得分:3)
select id, date, hour, comment from
(
select row_number() over(partition by id, day order by hour desc) as rn,
* from gdoshistorial ) t
where rn = 1
您可以使用row_number
获取每天的最新信息和身份证。
注意:上面的查询会为您提供每天的最新评论。如果您只需要最新的评论,无论白天, 改变
row_number() over(partition by id, day order by hour desc) as rn
到
row_number() over(partition by id order by day desc, hour desc) as rn
答案 1 :(得分:0)
SELECT TOP 1 *
FROM (
SELECT gdoshistorial.c1 AS ID
,max(gdoshistorial.c3) AS [DAY]
,max(gdoshistorial.c4) AS [TIME]
,gdoshistorial.c6 AS COMMENT
FROM gdos
LEFT JOIN gdoshistorial ON GDOSHISTORIAL.c1 = gdos.c1
WHERE gdos.c1 = gdoshistorial.c1
AND gdoshistorial.c1 = '00050064'
GROUP BY GDOSHISTORIAL.c1
,GDOSHISTORIAL.c6
) v
ORDER BY
[DAY] DESC
,[TIME] DESC