代码之家  ›  专栏  ›  技术社区  ›  Ege Bayrak

在sql server lead中使用where子句

  •  1
  • Ege Bayrak  · 技术社区  · 6 年前

    我在写一个问题 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    |
    +----------------+---------------------+---------------------+--------------+------+
    

    但当我检查返回身份证的细节时

    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 |
    +---------------------+----------------+-------------------------+
    

    基本上,我想在我的第一个查询中确保 只比较相同的记录 活动类型ID 但是我找不到怎么做。

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

    1 回复  |  直到 6 年前
        1
  •  2
  •   pim    6 年前

    实现这一目标的关键是 , 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