如何编写一条简单的SELECT语句,将报告限制在列值的前5位?
发布于 2010-02-21 23:20:01
您必须按该列值进行排序,可能按降序排列,这取决于您所说的"top 5“的含义;并且只获取顶部的5行。
使用MySQL,你会得到类似这样的东西,我会说:
select *
from your_table
where ...
order by your_column desc
limit 5
使用MSSQL server时,您没有limit
,但可以使用top
:
select top 5 *
from your_table
where ...
order by your_column desc
发布于 2010-02-21 23:53:55
我们不要忘记SQL Server WITH TIES。如果前6个值相同,则将从6个值中随机选择前5个值
SELECT TOP 5 WITH TIES... ORDER BY col DESC
发布于 2010-05-05 12:01:50
Sybase
返回前n行。
select top n * from table order by column
这不起作用,因为top是一个关键字,而不是一个函数:
select top(n) * from table order by column
使用set rowcount
对多个查询应用限制
set rowcount n
select * from table order by column
...
set rowcount 0
MySQL
MySQL docs
返回从第m行开始的前n行。
select * from table limit m, n order by column
SQL Server
返回前n行
select top n from table order by column
甲骨文
返回前n行
select *
from table
where rownum < 5
order by column
SQLite
SQLite docs
返回前n行
select * from table order by column limit(n)
返回从m行开始的前n行
select * from table order by column limit(m,n)
返回前n行
select * from table order by column limit(n) offset(m)
Postgres
Postgres docs
返回前n行
select * from table order by column limit(n)
返回从m行开始的前n行
select * from table order by column limit(n) offset(m)
如果我错过了任何数据库或行限制方法,请发表评论,我将添加它。谢谢!
https://stackoverflow.com/questions/2306303
复制相似问题