This lecture is on complex query SQL server, topic covered are: • OUTPUT Clause • RANK(), ROW_NUMBER() and DENSE_RANK() Function • Query Optimization and Use of execution plan.
Click Here to see full article and download sql script
----Basic but important functions --ROW_NUMBER() --RANK() --DENSE_RANK() --NTILE()
--ROW_NUMBER() --Returns a sequential row number with in partition of result set use Northwind; SELECT ROW_NUMBER() over(order by productid) as [Row No.], ProductName from Products;
----Getting alternate rows ------Odd Row select * from (SELECT ROW_NUMBER() over(order by productid) as [Row No.], ProductName from Products) p where p.[Row No.]%2=1; ------Even Row select * from (SELECT ROW_NUMBER() over(order by productid) as [Row No.], ProductName from Products) p where p.[Row No.]%2=0; ------Row Between select * from (SELECT ROW_NUMBER() over(order by productid) as [Row No.], ProductName from Products) p where p.[Row No.] Between 5 and
... Read more »
Their are many approaches to get alternate record from SQL server database table. Here i have discussed 2 approaches
1. Complex Query
2. Using Views
Complex Query: SELECT * from (SELECT ROW_NUMBER() OVER(ORDER BY Employee_id) as RowNumber, * from employees) T where t.RowNumber%2=0
Using Views:
CREATE VIEW with_rownumber
as
SELECT ROW_NUMBER() OVER(ORDER BY Employee_id) as RowNumber,* from employees;
SELECT * from with_rownumber where RowNumber%2=0
The approach preferred here is using VIEW because:
1. Easy to understand.
2. In future if you need to perform any operation related to RowNumber
then you don't need to create another complex query. You could use view
having rownumber column in it.