r/SQL • u/Simebaby • May 14 '22
MS SQL SQL Server - select only the row with the most recent datetime value in a column
Hi All
I'm trying to select *only* the row with the most recent value from a table. This is what I have, which I thought was working but turns out not to be:
select [Column A], max([Column B]) alias ,[Column C] from [Table]
where [Column A] = 'some value'
group by [Column A],[Column C]
This seems to work if the rows returned have the same data in Column C, but if the values in Column C differ, multiple rows are returned.
Any idea how I can get *just* the row with the most recent value in Column B? I do need the value of Column C for *that record* to be returned as well.
I should probably add that the above select is actually used in a left join rather than being stand-alone.
Ta
Si
5
u/r3pr0b8 GROUP_CONCAT is da bomb May 14 '22
2
u/Simebaby May 14 '22
Just to add some detail - given all the rows in [Table] where [Column A] = ‘some value], I need the row with the most recent datetime in [Column B]. There will be multiple rows matching the [Column A] criteria, and I need the value in [Column C], but only for the most recent row.
I suspect the fact that I’m grouping by Cols A and C mean that all differing values of C will be returned - but I’m not sure how to get round that.
1
u/Able_Translator_1445 May 14 '22
Select top 1 [Column A], [Column B], [Column C]
from [Table]
order by [Column B] desc
1
u/stanleypup May 14 '22
If I'm understanding your problem correctly, you can either subquery to get your max col b value, grouped only by col a and then join on cols a&b, or add a column with a window function that gives you max value partitioned by col a, and use a having clause to find records where col b and your new column are the same.
The latter method should be more computationally efficient
0
u/harambeface May 15 '22
Multiple ways to solve including the first_value analytical function, but analytical functions are slow. My preferred way would be
Select t1.ColA , t1.ColB ,t1.ColC From table t1 Where t1.colB=(select max(t2.ColB) from table t2 where t2.ColA=value)
0
u/[deleted] May 14 '22
[deleted] — view deleted comment