I'm trying to convert a Linq query to SQL. My Linq query looks like this:
from s in Somethings
where s.CreatedTime >= new DateTime(2010, 01, 01)
where s.CreatedTime < new DateTime(2010, 02, 01)
group s by s.Data into grouping
select grouping.OrderByDescending(s => s.CreatedTime)
.ThenByDescending( s => s.UpdatedTime)
.First();
In words, that is supposed to get all things from a certain month. Then group them by a specific key. For each key, I want the most recently created element. If two elements with the same key were created at the same time, I want to break ties by most recently updated.
So far I have this for SQL
SELECT s1.*
FROM Somethings s1
JOIN (
SELECT s.Date AS Data, MAX(CreatedTime) AS CreatedTime
FROM Somethings s
WHERE s.CreatedTime >= '20100101'
AND s.CreatedTime < '20100201'
GROUP BY s.Data
) s2 ON s1.Data = s2.Data
AND s1.CreatedTime = s2.CreatedTime
That works, but I can't control how ties are broken.
What I really want is a way to arbitrarily sort each grouping like I can in Linq. I want to define my own aggregation function that takes a set of rows, and returns one row. Is this possible in SQL, or is Linq more expressive? SQL's aggregation functions MAX, MIN, COUNT etc don't seem to be first class functions like their equivalent in Linq is. Of course it could just be my lack of knowledge of SQL.
Here's a made up example to further illustrate what I want to do in SQL:
SELECT (SELECT *
FROM grouping
ORDER BY CreatedTime DESC, UpdatedTime DESC
LIMIT 1)
FROM Somethings s
WHERE s.CreatedTime >= '20100101'
AND s.CreatedTime < '20100201'
GROUP BY s.Data AS grouping
In this example, my illegal inner query is serving the same role as an aggregation function.