mthor
mthor

Reputation: 46

DISTINCT and GROUP BY with SQL Server

I have the following table (sql server) and i'm looking for a query to select the last two rows with all fields:

In MySQL its an easy task - but with SQL Server all fields have to be contained in either an aggregate function or the GROUP BY clause. But that results in field combinations that does not exist.

Is there a way to handle this?

Thanks in advance!

Upvotes: 0

Views: 591

Answers (1)

mthor
mthor

Reputation: 46

Solution

Based on the comment from Andrew Deighton i did this:

SELECT *
FROM (
       SELECT
         id,
         type_id,
         some_value,
         created_at,
         ROW_NUMBER()
         OVER (PARTITION BY type_id
           ORDER BY created_at DESC) AS row
       FROM test_sql
     ) AS ts
WHERE row = 1
ORDER BY row

Conclusion: No need for GROUP BY and DISTINCT.

Upvotes: 1

Related Questions