我有一个如下表。数据之间没有周期性,所以我不能使用row_number((或rank之类的函数。
**Column1** | **Column2** | **Timestamp**
Station1 | Data1 | Date1
Station1 | Data2 | Date2
Station1 | Data1 | Date3
Station1 | Data2 | Date4
Station1 | **Data3** | Date5
Station1 | Data2 | Date6
Station2 | Data1 | Date7
Station2 | Data2 | Date8
Station2 | **Data3** | Date9
Station2 | Data2 | Date10
第2列中的普通数据与Data1和Data2类似,但当它将Data3插入第2列时,它打破了Data1和Data2之间的周期性。我不希望在Data3之后的查询中看到数据检索。我希望它像下面这样。
**Column1** | **Column2** | **Timestamp**
Station1 | Data1 | Date1
Station1 | Data2 | Date2
Station1 | Data1 | Date3
Station1 | Data2 | Date4
Station2 | Data1 | Date7
Station2 | Data2 | Date8
我该怎么做才能达到这个结果?提前谢谢。
你似乎想要"data1";只有当下一行是"0"时;data2";以及";data2";仅当前一行是"0"时;data1";。因此:
select t.*
from (select t.*,
lag(column2) over (partition by column1 order by timestamp) as prev_column2,
lead(column2) over (partition by column1 order by timestamp) as next_column2
from t
) t
where (column2 = 'data1' and next_column2 = 'data2') or
(column2 = 'data1' and prev_column2 = 'data1')
您只想显示Data1和Data2行,但只想显示前一行是其他数据的行。换句话说,您希望显示交替的Data1和Data2行。这可以通过LAST_VALUE
:实现
select column1, column2, timestmp
from
(
select
column1, column2, timestmp,
last_value(case when column2 in ('Data1', 'Data2') then column2 end ignore nulls)
over
(order by timestmp rows between unbounded preceding and 1 preceding) as last_col2
from mytable
)
where column2 in ('Data1', 'Data2')
and decode(column2, last_col2, 'same', 'different') = 'different'
order by timestmp;
演示:https://dbfiddle.uk/?rdbms=oracle_18&fiddle=c8611e24eb0d54ba65e89391d11332cd
(但是,如果允许总是有Data3行加上后面的一行要删除,那么您可以使用LAG
,并忽略column2 = '**Data3**' or lag(column2) = '**Data3**'
所在的所有行。(
简化格式:
SQLFiddle
SELECT X.column1, x.column2, x.timestamp FROM
(
SELECT A.*, LEAD(COLUMN2) OVER(ORDER BY COLUMN1, column2) NEXT_VALUE
FROM TABLE1 A
) X WHERE 'Data3' not IN (COLUMN2, NEXT_VALUE)
ORDER BY 1, 2;