我想查找每个公司代码的前一天价格和第二天的价格 我使用此查询:
WITH CTE AS (
SELECT
rownum = ROW_NUMBER() OVER (ORDER BY p.CompanyCode,p.Date),
p.Price
FROM Table1 p
)
SELECT
prev.price PreviousValue,
CTE.price,
nex.price NextValue
FROM CTE
LEFT JOIN CTE prev ON prev.rownum = CTE.rownum - 1
LEFT JOIN CTE nex ON nex.rownum = CTE.rownum + 1
GO
但它非常慢,我希望更快地查询
答案 0 :(得分:1)
您可以在SqlServer2012版本之后使用此查询
SELECT CompanyCode,[Date],
LAG(p.Price) OVER (ORDER BY p.CompanyCode,p.[Date]) PreviousValue,
p.Price,
LEAD(p.Price) OVER (ORDER BY p.CompanyCode,p.[Date]) NextValue
FROM Table1 p
order by CompanyCode,[Date]