How to page a View - sql-server

I have a view in my sql server 2005 db.
I'm using Pythons PyMsSQL to select rows form the view. I'm not necessarily selecting all the rows in the view with this select. For example, I might select based on name or date etc.
How can I page this view? That is, how can I select row 0 to 9, or rows 10 to 19 etc.
Thanks for your help,
Barry

One option is to use the ROW_NUMBER window function to
add a number you can select on
using an ORDER BY date, name or any other column that guarantees the order between subsequent runs.
SQL Statement
SELECT *
FROM ( SELECT ROW_NUMBER() OVER ( ORDER BY Date ) AS RowNum, *
FROM AView
) AS AView
WHERE RowNum BETWEEN 1 AND 9

Related

SQl Query with even distribution of samples

Is there a way to query SQL to get an even distribution of samples. For example if one of my fields is a State field... I want to query top 5000 results with (100 from each state)... Or another example, if I have a field that says whether a client is a new client or an existing client, and I want the top 500 results where 250 are new clients and 250 are existing clients.
I am trying to avoid two different queries that I have to manually combine the results.
You can do this by using ROW_NUMBER. You partition your data on one or more columns, so the row numbering starts from 1 in every partition. You then select the top x rows and ORDER BY the row number column.
e.g.
WITH cte
AS
(
SELECT *,ROW_NUMBER() OVER (PARTITION BY StateName ORDER BY NEWID() ) AS RN
FROM dbo.Sales
)
SELECT TOP 5 *
FROM cte
ORDER BY RN;

How to calculate the days between 2 dates from 2 successive IDs

I need some help to create a new column in a database in SQL Server 2008.
I have the following data table
Please have a look at a snapshot of my table
Table
In the blank column I would like to put the difference between the current status date and the next status' date. And for the last ID_Status for each ID_Ticket I would like to have the difference between now date and it's date !
I hope that you got an idea about my problem.
Please share if you have any ideas about how to do .
Many thanks
kind regards
You didn't specify your RDBMS, so I'll post an answer for both since they are almost identical :
SQL-Server :
SELECT ss.id_ticket,ss.id_status,ss.date_status,
DATEDIFF(day,ss.date_status,ss.coalesce(ss.next_date,GETDATE())) as diffStatus
FROM (
SELECT t.*,
(SELECT TOP 1 s.date_status FROM YourTable s
WHERE t.id_ticket = s.id_ticket and s.date_status > t.date_status
ORDER BY s.date_status ASC) as next_date)
FROM YourTable t) ss
MySQL :
SELECT ss.id_ticket,ss.id_status,ss.date_status,
DATEDIFF(ss.date_status,ss.coalesce(ss.next_date,now())) as diffStatus
FROM (
SELECT t.*,
(SELECT s.date_status FROM YourTable s
WHERE t.id_ticket = s.id_ticket and s.date_status > t.date_status
ORDER BY s.date_status ASC limit 1) as next_date)
FROM YourTable t) ss
This basically first use a correlated sub query to bring the next date using limit/top , and then wrap it with another select to calculate the difference between them using DATEDIFF().
Basically it can be done without the wrapping query, but it won't be readable since the correlated query will be inside the DATEDIFF() function, so I prefer this way.

SQL Server 2008 - How to show rows between 1001 to 2000

I am using SQL Server 2008. With help of TOP clause in SQL Server I have run following query to display the first 1000 rows from my table Department
Select TOP 1000 *
from Department;
Now I need to display the next 1000 data from the same table. Can anybody help me to find a solution for the this?
You can use the ROW_NUMBER function to get the number of the row, and then take the numbers from X to Y. Below query is assuming that you want the results ordered by ID:
WITH OrderedDepartments AS
(
SELECT ID, Name,
ROW_NUMBER() OVER (ORDER BY ID) AS RowNumber
FROM Department
)
SELECT ID, Name
FROM OrderedDepartments
WHERE RowNumber BETWEEN 1001 AND 2000;
you can try something like:
SELECT *
FROM (
SELECT *, ROW_NUMBER() OVER (ORDER BY DEPARTMENT_NAME) AS rownum
FROM DEPARTMENT
) AS t
WHERE t.rownum BETWEEN 1001 AND 2001
Best way is use "FETCH (Transact-SQL)", more info and sample available in following link,
FETCH (Transact-SQL)

SQL Server 2008 default select top n row

In the MS SQL Management studio you can select
top n row as an action in the table menu.
I know how configuring the number of returned rows.
I want to now if there is a way to configure to return rows in desc ordering ?
If it were possible to determine if there was an identity primary key you could default to using that as the descending order, this would be usefull for showing the most recent items first? But there doesn't seem to be a way to get at the template used to generate the SQL so I think the answer is NO.
You have to modify the generated query and add an ORDER BY clause to it. Management Studio can't know by which column you want to sort.
SELECT *
FROM
(
SELECT t.*, ROW_NUMBER() OVER(order by ... desc) rn
FROM table t
)
WHERE rn < requiredQuantity

What's the best method to do paging in my ASP page

What's the best method to do paging in my ASP page when displaying a list of items?
I knew that there is no equivalent to MySQL's LIMIT clause present in SQL Server, either 2000 or 2005.
How can I retrieve some particular records (Records 20 to 30) from the DB?
Do i need to fetch all the records from the database and do something in my ASP page to display the required records?
Whats the best method to do paging in my ASP page when displaying a list of items ?
I just want to add one more feature to Mr. Wheat's answer. Why not u are trying to use the Take () and Skip() feature of linq(obviously if u are using dotnet framework 3.5+)
It is indeed helpful while working with large datasets.
Have a look
Using Take and Skip method in LINQ queries
I knew that there is no MySQL LIMIT clause present in SQL server(both 2000 and 2005 should support).how can i retrieve some particular records (Record 20 -30) from DB ?
You can do this in SQLSERVER 2005+ by using ranking function Row_Number() among other alternatives. A sample example is included herewith
First I am creating a dummy table and inserting some 50 records
declare #tbl table(name varchar(50),age int)
;with num_cte as
( select 1 as rn
union all
select rn+1 from num_cte where rn<50
)
insert #tbl
select names ,rn + 20 ageval
from num_cte
cross apply( select 'name' + CAST(rn as varchar(2)) AS names) names
select * from #tbl
Now by using the Row_Number() function I am picking up records between 20 & 30
select name,age from(
select ROW_NUMBER()over (order by age) as rownum,name,age from #tbl) X
where X.rownum between 20 and 30
However, for achieving the same in SQL SERVER 2000 the below query will help
select name,age from(
select t1.name,t1.age,
(select count(*)+1 from #tbl where name<>t1.name and age<=t1.age) rownum
from #tbl t1
)X(name,age,rownum)
where rownum between 20 and 30
Please see:
Paging In ASP.NET
Data Access Tutorials
GridView Examples for ASP.NET 2.0: Paging and Sorting the GridView's Data
SQL Server 2005 Paging – The Holy Grail
Youd need to use ROW_NUMBER (SQL Server 2005+)
SELECT * FROM
(SELECT a.*, ROW_NUMBER() OVER (ORDER BY hire_date) rn
FROM hr.employees AS OF TIMESTAMP (TIMESTAMP '2009-01-29 10:30:00') a)
WHERE rn BETWEEN 10 AND 19
Related answer
Using ROW_NUMBER, you are numering and sorting the inherently unsorted group (the table). Once you have an ordered set instead of just a set, you can now the sentence "I want all the rows from 10 to 19" makes sense.
You will have to use ASP code to keep both the upper and lower elements, so you can ask for the next or previous subset of rows to show.

Resources