Sql server 在Sql Server LEAD中使用where子句

Sql server 在Sql Server LEAD中使用where子句,sql-server,Sql Server,我正在写一个查询,涉及潜在客户。我最近发现了它,让我的生活变得轻松了很多。但我有一个小问题 我的问题是: SELECT a.ActivityTypeID,acs.ActivityStatementID, LEAD(acs.ActivityStatementID) OVER (PARTITION BY StatementCode ORDER BY a.ActualDateTime DESC) PreviousStatementID, acs.Value as CurrentValue, 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
只比较具有相同
activitypeid
的记录,但我找不到如何进行比较

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

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

实现这一点的关键是在
PARTITION BY
子句中添加
、ActivityId

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

LEAD
返回数据子集中的下一行的值,该行由
ORDER by
确定,由
PARTITION by
子句定义。这不是您想要的吗?按ActivityTypeID分区按ActivityTypeID分区会导致相同的活动结果。我想将一个活动的结果与以前相同类型的活动进行比较。相同的activityType,不同的activity ID,不同的ActualDateTime。语句代码在活动之间是相同的。您希望将行之间相同的内容放在
PARTITION BY
子句中。如果需要相同的
StatementCode
ActivityTypeID
值,则需要在
分区中同时使用这两个值。