带有左外连接的X的SQL增量计数

时间:2014-01-10 13:29:47

标签: sql-server count increment

我正试图以StSe.ID

为基础逐步增加StVS.ID的增量计数

e.g。期望的结果:

enter image description here

到目前为止我的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

1 个答案:

答案 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排序(假设它的时间递增)但是如果你有一个更好的字段,比如时间戳,建议按顺序排序。