2016-11-16 111 views
1

我有一個包含下面的結構數據的表:SQL選擇條件

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的地方有一個操作型其次

我試圖像幾個方法:

 
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 

,但沒能得到準確的結果。

任何幫助,將不勝感激。

感謝, Ĵ

+1

顯示我們預期的結果也是如此。 – jarlh

+1

你正在使用哪個sql server – mansi

+1

你想要Id 3或4的結果? –

回答

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

補充一下,sagi擊敗了我;-) –

+0

想通了:我不得不在由dt_created排序的同時通過ObjectName使用分區。 – Jinish

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()功能裏面,因爲每個ID都是唯一的。

1

只是使用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 
+0

非常感謝,所有的評論幫助。至少我能夠發現我對這個問題的理解存在差距。我需要抓取記錄,其中17緊接在對象名稱周圍,因此對於每個ObjectName。我更新了表格結構。所以,只有在表格數據看起來像帖子中的數據時,我才需要記錄3和4。謝謝 – Jinish