我不确定这在单独的T-SQL中是否可行,或者我是否应将其移至c#并在那里进行。我有一个像这样的表格设置:
Tracking
--------
ID int
Hash varchar
pageID int
该表正在跟踪用户如何通过网站旅行。每个页面加载一个新行添加。每个会话都获得一个新哈希。示例数据:
1 3pm6Qav1Vdf 4
2 3pm6Qav1Vdf 7
3 3pm6Qav1Vdf 41
4 3pm6Qav1Vdf 2
因此,执行以下操作将获得会话的跟踪(第一页到最后一页):
SELECT * from Tracking WHERE hash='3pm6Qav1Vdf' ORDER BY ID;
如果可能,我想获得的是:
1 3pm6Qav1Vdf NULL 4
2 3pm6Qav1Vdf 4 7
3 3pm6Qav1Vdf 7 41
4 3pm6Qav1Vdf 41 2
它会添加一个列,列出上一个pageID以及当前的pageID。在T-SQL中是这样的,还是应该将它移到c#?
答案 0 :(得分:3)
DECLARE @hash VARCHAR(32);
;WITH x AS
(
SELECT ID, pageID, rn = ROW_NUMBER() OVER (ORDER BY ID)
FROM dbo.Tracking
WHERE Hash = @hash
)
SELECT x.ID, Hash = @hash, PreviousPage = y.pageID, x.pageID
FROM x LEFT OUTER JOIN x AS y
ON x.rn = y.rn + 1
ORDER BY x.ID;
答案 1 :(得分:1)
此CTE将允许您访问上一行。如果您愿意,可以将WHERE子句移动到CTE部分,或者您可以完全将其留下以使整个行集具有先前的值。
with cte as (
select *, row_number() over (partition by hash order by id) as RN
from Tracking
)
select c.id, c.hash, cprev.id as previd, c.id
from cte c
left join cte cprev on c.hash = cprev.hash and c.rn = cprev.rn + 1
where
c.hash = 'yourhash'