开发者

T-SQL: How to retrieve a 1/2 of total row count (basing on some criteria) or 50 first rows?

I wondering about how in T-SQL can I retrieve - let's say - 1/2 of total row count开发者_运维知识库 form a table (basing on some criteria) or even the first 50 rows (basing on some criteria too) ?


To select the top 50 rows:

SELECT TOP 50 *
FROM table1
WHERE ...
ORDER BY ...

To select the first half of the result set use PERCENT:

SELECT TOP 50 PERCENT *
FROM table1
WHERE ...
ORDER BY ...

Remember to add an ORDER BY if you want the results to be consistent.


First:

SELECT TOP 50 PERCENT a, b, c FROM table

Second:

SELECT TOP 50 a, b, c FROM table

As a rule, it's not advisable to do this unless you are also providing an ORDER BY (and in those times where it will work perfectly well to leave out the ORDER BY, your code will be more understandable and more robust to changes in the details of the underlying tables if you put it in).

Paging (e.g. returning the x block of y rows) is more cumbersome in SQLServer than many other SQL-language relational databases (more cumbersome than just about all of them to be honest), but can be done with ROW_NUMBER:

WITH OrderedTable AS
(
  SELECT a, b, c, ROW_NUMBER() OVER (ORDER BY d) as rowNumber
  FROM table
)
SELECT a, b, c FROM OrderedTable
WHERE rowNumber between 31 and 40

Will select the third set of ten rows, ordered by column d.

This latter method is also needed when the limit comes from a variable, as TOP does not allow something like TOP @number.


using SQL TOP Clause

SQL Server Syntax

 SELECT TOP number|percent column_name(s)
   FROM table_name

 example : 

   SELECT TOP 50 PERCENT * FROM tablename

MySQL Syntax

SELECT column_name(s)
FROM table_name
LIMIT number

Oracle Syntax

SELECT column_name(s)
FROM table_name
WHERE ROWNUM <= number


Following works in MS SQL 2005 and 2008

select top 50 PERCENT * from x
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜