I have to migrate some SQL from PostgreSQL to SQL Server (2005+). On PostgreSQL i had:
select count(id) as count, date
from table
group by date
order by count
limit 10 offset 25
Now i need the same SQL but for SQL Server. I did it like below, but get error: Invalid column name 'count'. How to solve it ?
select * from (
select row_number() over (order by count) as row, count(id) as count, date
from table
group by date
) a where a.row >= 25 and a.row < 35
You can’t reference an alias by name, at the same scope, except in an ending
ORDER BY(it is an invalid reference inside of a windowing function at the same scope).To get the exact same results, it may need to be extended to (nesting scope for clarity):
This can be shortened a little bit as per mohan’s answer.
In SQL Server 2012, it’s much easier with OFFSET / FETCH – closer to the syntax you’re used to, but actually using ANSI-compatible syntax rather than proprietary voodoo.
I blogged about this functionality in 2010 (lots of good comments there too) and should probably invest some time doing some serious performance tests.
And I agree with @ajon – I hope your real tables, columns and queries don’t abuse reserved words like this.