SQL选择条件

时间:2016-11-16 11:44:10

标签: sql sql-server select

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

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

我想获取记录的ID,其中有一个操作类型 17 ,然后是 26

我尝试过几种方法:

select abc.id, abc.PreviousOperationType
from (select id,
       case 
            when OperationType = 26
            then 
                lead(OperationType, 1, 0) over (partition by id order by id)
            else 
                null 
            end as PreviousOperationType
from operation
where dt_created between '2015-09-20' and '2015-09-30') as abc
where abc.PreviousOperationType is not null and abc.PreviousOperationType= 17

但无法获得准确的结果。

任何帮助都将不胜感激。

谢谢, Ĵ

3 个答案:

答案 0 :(得分:3)

你很亲密:

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都是唯一的。

答案 1 :(得分:1)

以下查询为您提供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;

答案 2 :(得分:1)

只使用没有Lead()函数的ROW_NUMBER()函数,因此也兼容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