我有一个表格,我想要选择最后10%的行,偏移10%(所以我想选择最后80-90%的数据)。
我写了以下查询
SELECT TOP 10 PERCENT
[col1], [col2]
FROM [table]
ORDER BY [col1] DESC
OFFSET 10 ROWS
但是我收到以下错误:
第5行:'OFFSET'附近的语法不正确。
我做错了什么?我使用的Microsoft SQL Server 2012应与OFFSET
答案 0 :(得分:4)
尝试这样的事情......
SELECT TOP (50) PERCENT *
FROM (
SELECT TOP (20) PERCENT
[col1]
,[col2]
FROM [table]
ORDER BY [col1] DESC
)T
ORDER BY [col1] ASC
答案 1 :(得分:1)
对于您的错误消息,您的数据库是否设置为backwards compatibility mode?
offset
表达式只允许您指定行号,而不是百分比。您可以选择80-90百分位数,如:
select *
from (
select 100.0 * row_number() over (order by FirstName desc) /
count(*) over () as perc_pos
from YourTable
) as SubQueryAlias
where 80 <= perc_pos and perc_pos < 90
答案 2 :(得分:0)
你可以使用一个简单的好旧而不是:
SELECT TOP 10 PERCENT [col1], [col2]
FROM [table]
WHERE [col1] NOT IN (
SELECT TOP 10 PERCENT [col1]
FROM [table]
ORDER BY [col1] DESC
)
ORDER BY [col1] DESC
答案 3 :(得分:0)
如果您正在寻找一种呈现方式,例如在网页上显示数据块。
尝试
WITH Ordered AS
(
SELECT *,
ROW_NUMBER() OVER (ORDER BY ServerName) AS 'RowNumber'
FROM systems
)
SELECT *
FROM Ordered
WHERE RowNumber BETWEEN 11 AND 20
使用此代码,我可以为用户提供前10个,然后是第二个10(11-20),以此类推。
现在,请注意。如果您的数据频繁更改,则可能会受到影响,因为它将在完成查询时为您提供前10行(或50至60行)。
因此,如果添加了新数据,则会警告该列表。例如,如果您查看计算机列表,并且某人添加了一个名为“ AAA”的新服务器,并且您查看列表的中间位置,那么一个查询中的项目50可能是第二个查询中的项目49。 (我希望我不要再对此感到困惑了。)
答案 4 :(得分:-1)
select top 1 *
from Employee
where empid in (
select top 50 percent empid
from employee
order by empid
)
order by empid desc
答案 5 :(得分:-3)
declare @middle1 as int
set @middle1 = ((select COUNT(*) from [table] )+1)/2
declare @middle2 as int
set @middle2 = ((select COUNT(*) from [table] ))/2
select * from
(select ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) as R, * from [table] where (select COUNT(*) from [table] ) % 2 = 0) T2
where (T2.R - @middle2 = 0) or (T2.R- @middle1 = 0)
union
select * from
(select ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) as R, * from [table] where (select COUNT(*) from [table] ) % 2 != 0) T2
where T2.R - @middle1 = 0