SQL Server 2008中替代OFFSET ... FETCH NEXT

时间:2017-03-14 00:32:24

标签: sql-server sql-server-2008 sql-server-2008-r2

我在SQL Server中有一个class Animal(object): def __init__(self): self.legs = 2 self.name = 'Dog' self.color= 'Spotted' self.smell= 'Alot' self.age = 10 self.kids = 0 if __name__ == '__main__': animal = Animal() temp = vars(animal) for item in temp: print item , ' : ' , temp[item] #print item , ' : ', temp[item] , 表,我需要选择(比方说)按其upvotes计数排序的前10行,这是DB脚本:

posts

我需要一个有效的查询来根据upvotes的数量从帖子中选择下一个前10行。如何在SQL Server 2008中实现此目的?

重要编辑:我愚蠢地忘了提到我使用的是create database someforum go use someforum go create table users ( user_id int identity primary key, username varchar(80) unique not null ); create table posts ( post_id int identity primary key, post_time datetime, post_title nvarchar(32), post_body nvarchar(255), post_user int foreign key references users(user_id) ); create table votes ( vote_id int identity primary key, user_id int foreign key references users(user_id), vote_type bit, --upvote=true downvote=false post_id int foreign key references posts(post_id) ); insert into users values ('foo'),('bar') insert into posts values (getdate(),N'a post by foo',N'hey',1), (getdate(),N'a post by bar',N'hey!',2) insert into votes values (1,0,1),(2,0,1),(1,1,2),(2,1,2) --first post downvoted by its poster (foo) and bar, second post was upvoted by both users 尚未引入的SQL Server 2008 R2。我还修改了目前与我的需求无关的内容。

4 个答案:

答案 0 :(得分:1)

这就是我想要的(不使用score列):

select top 10 p.post_title,sum(case when vote_type=1 then 1 else -1 end) as score
from posts p join votes v on p.post_id = v.post_id
group by p.post_title 

关于OFFSET… FETCH NEXT的替代方案,我在DBA中找到了一个很好的解决方案

答案 1 :(得分:0)

  1. 没有“最好”;但工作命令可能涉及select top 10 ... order by Score desc。我发现您的posts表格 没有 一个Score列(聚合和非规范化投票),但是:您可以更改

  2. OFFSET / FETCH clause

答案 2 :(得分:0)

您可以使用gridView对象来显示结果:这将允许用户使用您的部件上最少的代码对各个列进行排序,并允许分页,在gridView的底部包含编号的链接,允许用户浏览结果列表。

使用包含10行的gridView将允许显示前10名,用户还可以选择移动排序列表的其余部分。

答案 3 :(得分:0)

1)您可以通过此查询计算和过滤

SELECT * FROM (
    SELECT *, COUNT(*) as upvotes FROM posts AS p INNER JOIN votes AS v ON (p.post_id = v.post_id) WHERE v.type = true
) as v_post  OFFSET 10 ROWS

2)您可以在查询结束时逐步移位(现在为10):FETCH NEXT 10FETCH NEXT 20等。