在Sql Server LEAD中使用where子句

时间:2018-05-31 08:51:37

标签: sql-server

我正在编写一个涉及LEAD的查询。我最近发现它并让我的生活变得更轻松。但我有一个小问题

我的问题是这个;

SELECT a.ActivityTypeID,acs.ActivityStatementID,
LEAD(acs.ActivityStatementID) OVER (PARTITION BY StatementCode ORDER BY a.ActualDateTime DESC) PreviousStatementID,
acs.Value as CurrentValue,
LEAD(acs.Value) OVER (PARTITION BY StatementCode ORDER BY a.ActualDateTime DESC) as Prev
FROM ActivityStatement acs 
   INNER JOIN Activity a on a.ActivityID = acs.ActivityID
WHERE a.CustomerID = 128077
and a.TenantID = 19
and a.ActualDateTime IS NOT NULL

我的查询结果中有一行是

+----------------+---------------------+---------------------+--------------+------+
| ActivityTypeID | ActivityStatementID | PreviousStatementID | CurrentValue | Prev |
+----------------+---------------------+---------------------+--------------+------+
| 397            | 849433              | 849609              | A            | A    |
+----------------+---------------------+---------------------+--------------+------+

但是,当我检查返回ID的详细信息时,

select acs.activitystatementid,a.ActivityTypeID,a.ActualDateTime from ActivityStatement acs
  inner join Activity a on a.ActivityID = acs.ActivityID
  where acs.ActivityStatementID IN (849433,849609)
  and a.CustomerID = 128077

我看到ActivityTypeID个记录不一样

+---------------------+----------------+-------------------------+
| activitystatementid | activitytypeid | ActualDateTime          |
+---------------------+----------------+-------------------------+
| 849433              | 397            | 2018-05-21 11:59:37.000 |
+---------------------+----------------+-------------------------+
| 849609              | 396            | 2018-05-21 11:59:05.000 |
+---------------------+----------------+-------------------------+

基本上,我想在第一个查询中确保LEAD仅比较具有相同ActivityTypeID的记录,但我无法找到该怎么做。

Sql Server版本是Sql Server 2016(SP1-CU3)

1 个答案:

答案 0 :(得分:2)

  

“...仅比较具有相同ActivityTypeID的记录”。

完成此操作的关键是, ActivityId子句中的附加PARTITION BY

SELECT a.ActivityTypeID,acs.ActivityStatementID,
LEAD(acs.ActivityStatementID) OVER (PARTITION BY StatementCode, ActivityId ORDER BY a.ActualDateTime DESC) PreviousStatementID,
acs.Value as CurrentValue,
LEAD(acs.Value) OVER (PARTITION BY StatementCode, ActivityId ORDER BY a.ActualDateTime DESC) as Prev
FROM ActivityStatement acs 
   INNER JOIN Activity a on a.ActivityID = acs.ActivityID
WHERE a.CustomerID = 128077
and a.TenantID = 19
and a.ActualDateTime IS NOT NULL