我正试图以StSe.ID
StVS.ID
的增量计数
e.g。期望的结果:
到目前为止我的SQL ..
Select top (1000)
StVS.ID AS 'SessionID',
StSe.ID AS 'Search ID',
--I need this to be an incremental count for search count based on Session ID
count (StVS.ID) AS 'Search ID sequence'
From Stats_VisitorSessions StVs
Left join Stats_VisitorSearches StSe WITH (NOLOCK) on StSe.SessionID=StVs.SessionID
Left join Stats_Visitors StV WITH (NOLOCK) on StV.VisitorID=StVs.VisitorID
group by StVS.ID, StSe.ID
Order by StVs.ID
答案 0 :(得分:2)
您可以使用ROW_NUMBER()
with Partition:
编辑 - 道歉,错过了LOJ中关于NULL
的观点:
Select top (1000)
StVS.ID AS 'SessionID',
StSe.ID AS 'Search ID',
CASE WHEN StSe.ID IS NULL
THEN 0
ELSE ROW_NUMBER() OVER (PARTITION BY StVS.ID ORDER BY StSe.ID ASC)
END AS Sequence
From Stats_VisitorSessions StVs
Left join Stats_VisitorSearches StSe on StSe.SessionID=StVs.SessionID
Left join Stats_Visitors StV on StV.VisitorID=StVs.VisitorID
group by StVS.ID, StSe.ID
Order by StVs.ID;
我按Searchid
排序(假设它的时间递增)但是如果你有一个更好的字段,比如时间戳,建议按顺序排序。