I have this table Test { Id:int, data:string } – a table with two columns and n rows.
Facts:
- Id is unique (and tells something about the order the items have been added)
- data can have duplicates
- if items are grouped by data all the Id are consecutive
In LINQ I would do something like :
class Row
{
public int Id { get; set; }
public string Data { get; set; }
}
public static class MyTestClass
{
public static void Test()
{
IEnumerable<Row> rows = new List<Row>
{
new Row { Id = 1, Data = "42"},
new Row { Id = 2, Data = "42"},
new Row { Id = 3, Data = "11"},
new Row { Id = 4, Data = "11"},
new Row { Id = 5, Data = "11"},
new Row { Id = 6, Data = "65"},
};
var result = rows.GroupBy(r => r.Data)
.OrderByDescending(g => g.First().Id)
.Select(g => g.Key)
.ToList();
var str = string.Join(" ", result);
Console.WriteLine(str);
}
}
This would print :
65
11
42
How do I write this in an effecient way in SQL (for MS SQL)? I’ve been around different soluions like "SELECT DISTINCT Data, Id FROM Test ORDER BY Id DESC" but this apparently this returns distinct based on both columns – which is obviously not what I want 🙂
Can you try this?
UPDATE:
Since Id should be with an aggregate function and it is irrelevant with the author’s requirement, hence i have used MAX function, any other function can be used , i guess.