I have a table:
Insert Date | Value1 | Value2 | Group |
---|---|---|---|
2023-01-01 | 123 | 135 | a |
2023-02-01 | 234 | 246 | a |
2023-01-02 | 456 | 468 | b |
2023-02-02 | 345 | 357 | b |
I would like to find for each group when it had the highest value and then from these dates choose the oldest.
for the above data: group a
has the maximum in February, group b
has the maximum in January, so the final result I expect is 2023-01-02
.
currently I do it like this:
SELECT MIN([Insert Date])
FROM (
SELECT [Insert Date], [RowNo] = ROW_NUMBER() OVER(PARTITION BY [Group] ORDER BY [Value1] DESC, [Insert Date] DESC) FROM table WITH(NOLOCK)
UNION
SELECT [Insert Date], [RowNo] = ROW_NUMBER() OVER(PARTITION BY [Group] ORDER BY [Value2] DESC, [Insert Date] DESC) FROM table WITH(NOLOCK)
) AS src
WHERE [RowNo] = 1
But I don't think this is the best available way.