【问题标题】:SQL select conditionsSQL 选择条件
【发布时间】:2017-03-30 14:27:48
【问题描述】:

我有一个包含以下结构数据的表:

Id | OperationType | ObjectName | dt_created
-- | ------------- | ---------- | ----------
1  | 4             | test.com   |  2015-08-30 23:23:57.000
2  | 7             | test.com   |  2015-08-30 23:23:57.000
3  | 17            | test.com   |  2015-08-30 23:23:57.000
4  | 26            | test.com   |  2015-08-30 23:23:57.000
5  | 8             | test.com   |  2015-08-30 23:23:57.000
6  | 4             | test.com   |  2015-08-30 23:23:57.000
7  | 17            | 123.com    |  2015-08-30 23:23:57.000
8  | 18            | 123.com    |  2015-08-30 23:23:57.000
9  | 26            | 123.com    |  2015-08-30 23:23:57.000
10 | 8             | 123.com    |  2015-08-30 23:23:57.000

我想获取操作类型 17 后跟 26

的记录的 ID

我尝试了一些方法,例如:

选择 abc.id, abc.PreviousOperationType 从(选择ID, 案子 当 OperationType = 26 然后 Lead(OperationType, 1, 0) over (partition by id order by id) 别的 空值 以 PreviousOperationType 结尾 从操作 其中 dt_created 在 '2015-09-20' 和 '2015-09-30' 之间)为 abc 其中 abc.PreviousOperationType 不为 null 且 abc.PreviousOperationType= 17

但无法获得准确的结果。

任何帮助将不胜感激。

谢谢, J

【问题讨论】:

  • 向我们展示预期的结果。
  • 你使用的是哪个sql server
  • 你想要 Id 3 或 4 的结果?
  • 看到dt_created 包含一个时间,您可能不想使用between,而是使用where dt_created >= '2015-09-20' and dt_created < '2015-10-01' 之类的东西,以免只指定最后一天的第一秒。

标签: sql sql-server select


【解决方案1】:

你很亲密:

select abc.id, abc.PreviousOperationType
from (select id,
             OperationType,
             lead(OperationType, 1, 0) over (order by id) NextOperationType
        from operation
        where dt_created between '2015-09-20' and '2015-09-30') abc
where abc.OperationType = 17 AND 
      abc.NextOperationType= 26

不需要在LEAD() 函数中使用partition by 子句,因为每个ID 都是唯一的。

【讨论】:

    【解决方案2】:

    以下查询为您提供 ID 3,因为它的类型为 17,并且后跟一条类型为 26 的记录。

    select id
    from
    (
      select 
        id,
        operationtype,
        lead(operationtype) over (order by dt_created) as next_operationtype
      from operation
    ) op
    where operationtype = 17 and next_operationtype = 26;
    

    【讨论】:

    • 该死,sagi 打败了我 ;-)
    • 想通了:在按 dt_created 排序时,我必须使用 ObjectName 分区。
    【解决方案3】:

    只使用 ROW_NUMBER() 函数而没有 Lead() 函数,因此也兼容 sql server 2008 和 2005 :)

    ;WITH X AS (
    Select * 
           ,ROW_NUMBER() OVER (ORDER BY ID) rn
    from TableName )
    SELECT x.*
    FROM X x
    INNER JOIN X y ON x.rn + 1 = y.rn 
                  AND x.OperationType = 17
                  AND y.OperationType = 26
    

    【讨论】:

    • 非常感谢大家,所有 cmets 都提供了帮助。至少我能够确定我对这个问题的理解的差距。我需要获取 17 之前紧跟 26 围绕对象名称旋转的记录,因此对于每个 ObjectName。我已经更新了表结构。所以,只有当表数据看起来像帖子中的数据时,我才需要记录 3 和 4。谢谢
    猜你喜欢
    • 2010-11-05
    • 2018-03-08
    • 1970-01-01
    • 2021-09-11
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-04
    相关资源
    最近更新 更多