Sql server 查询以从包含ORDERBY子句的当前行中查找上一行和下一行
我执行以下查询:Sql server 查询以从包含ORDERBY子句的当前行中查找上一行和下一行,sql-server,sql-server-2008,Sql Server,Sql Server 2008,我执行以下查询: SELECT quotesid FROM quotestable WHERE quotesauthor LIKE '%Mahatma%' ORDER BY popularity DESC 这给了我以下结果:quotesid-是主键 968 158 159 160 161 我的要求: 我需要下一个和上一个quotesid顺序,例如,如果我在158记录。下一个和上一个值应该分别是159和968,我需要在单个查询中使用这两个值 我的问题 这是行不通的。这只给了我
SELECT quotesid
FROM quotestable
WHERE quotesauthor LIKE '%Mahatma%'
ORDER BY popularity DESC
这给了我以下结果:quotesid-是主键
968
158
159
160
161
我的要求:
我需要下一个和上一个quotesid顺序,例如,如果我在158记录。下一个和上一个值应该分别是159和968,我需要在单个查询中使用这两个值
我的问题
这是行不通的。这只给了我一张唱片——159张。
有没有一种方法可以编写单个查询并获得所需的结果
小提琴:
我想这会给你你想要的:
;WITH t AS (
SELECT *, ROW_NUMBER() OVER (ORDER BY popularity DESC) rn
FROM quotestable
WHERE quotesauthor LIKE '%Mah%')
SELECT *
FROM t
WHERE 1 = ABS(t.rn - (SELECT rn FROM t WHERE quotesid = 158))
您可以使用此选项将上一行和下一行合并为一行:
;WITH t AS (
SELECT *, ROW_NUMBER() OVER (ORDER BY popularity DESC) rn
FROM quotestable
WHERE quotesauthor LIKE '%Mah%')
SELECT t1.quotesid, t2.quotesid PrevID, t3.quotesid NextID
FROM t t1
LEFT JOIN t t2 ON t1.rn = t2.rn - 1
LEFT JOIN t t3 ON t1.rn = t3.rn + 1
WHERE t1.rn = (SELECT rn FROM t WHERE quotesid = 158)
也许,这对你有用。它给出您的查询行号索引,然后将外部联接本身左移+1和-1记录,以生成[next]和[previous]列 结果:
quotesid Next Previous
------------------------
968 158 NULL
158 159 968
159 160 158
160 161 159
161 NULL 160
sql fiddle:
从quesid>=158或quesid order by primary key的表格@venkatselect*发布您想要的输出。问题是我需要一个不同键的订单。我建议你再增加一个名为“受欢迎程度和顺序”的专栏。它会起作用,因为你的人气是1,2,3,4,5,。请将100200,90101,5之类的值混洗,然后重试。@Venkat ok更新sql FIDLE并回答。原则上,查询是按流行度描述a排序的。当流行度不为空时,它似乎工作得很好。如果该值为空,则无法正常工作。@Venkat我检查了您的链接,但只能看到单选,没有数据。我还尝试了空值查看此链接:并且似乎效果良好。这不起作用。让我输入SQLFIDLE并向这里的每个人打开这个查询。
with cte as
(
select quotesid, ROW_NUMBER() over (order by popularity desc) as [RowNo]
from quotestable
)
select cte.quotesid, [next].quotesid as [Next], [prev].quotesid as [Previous]
from cte left outer join cte as [next] on cte.RowNo = ([next].RowNo - 1)
left outer join cte as [prev] on cte.RowNo = ([prev].RowNo + 1)
quotesid Next Previous
------------------------
968 158 NULL
158 159 968
159 160 158
160 161 159
161 NULL 160
select quotestable.quotesid, b.quotesid nextQuoteID, c.quotesid previousQuoteID from quotestable
join (
select a.quotesID, max(b.popularity) previousQuoteID, min(c.popularity) nextQuoteID
from quotestable a
left join quotestable b
on a.popularity > b.popularity
left join quotestable c
on a.popularity < c.popularity
where a.author like '%Mahatma%'
group by a.quotesid
) x
on quotestable.quotesid = x.quotesid
left join quotestable b
on b.popularity = x.previousquoteid
left join quotestable c
on c.popularity = x.nextquoteid
order by quotestable.popularity desc