我有这样的桌子:
+---------+----------------+--------+-------+-------+
| ITEM NO | EFFECTIVE DATE | HEIGHT | WIDTH | DEPTH |
+---------+----------------+--------+-------+-------+
| 1 | 01/01/1980 | 01 | 01 | 01 |
| 2 | 03/16/1985 | 02 | 02 | 02 |
| 1 | 07/03/1985 | 01 | 02 | 01 |
| 3 | 08/01/1986 | 03 | 03 | 03 |
| 1 | 08/03/1986 | 02 | 02 | 01 |
| 3 | 09/01/1986 | 04 | 03 | 03 |
| 2 | 09/20/1987 | 02 | 06 | 02 |
| 3 | 10/01/1987 | 04 | 04 | 03 |
| 1 | 06/18/2000 | 03 | 02 | 01 |
+---------+----------------+--------+-------+-------+
我需要一个查询,当物品的高度发生变化时,它返回物品的编号和日期。因此,结果将是:
+---------+----------------+
| ITEM NO | EFFECTIVE DATE |
+---------+----------------+
| 1 | 01/01/1980 |
| 1 | 08/03/1986 |
| 1 | 06/18/2000 |
| 3 | 08/01/1986 |
| 3 | 09/01/1986 |
+---------+----------------+
所以,在显示的日期(包括其初始高度),项目3的高度变化了3倍,因此项目2的高度没有变化,因此被忽略,因此项目3的高度发生了两次变化,因此出现了两次。
感谢您的帮助!
这里是一个选择;它
height
(每个item_no
,由date
排序)(第14行)item_no = 2
)您在这里:
SQL> with test (item_no, effective_date, height) as
2 (select 1, date '1980-01-01', '01' from dual union all
3 select 2, date '1985-03-16', '02' from dual union all
4 select 1, date '1985-07-03', '01' from dual union all
5 select 3, date '1986-08-01', '03' from dual union all
6 select 1, date '1986-08-03', '02' from dual union all
7 select 3, date '1986-09-01', '04' from dual union all
8 select 2, date '1987-09-20', '02' from dual union all
9 select 3, date '1987-10-01', '04' from dual union all
10 select 1, date '2000-06-18', '03' from dual
11 ),
12 temp as
13 (select item_no, effective_date, height,
14 lag(height) over (partition by item_no order by effective_date) lheight,
15 row_number() Over (partition by item_no order by effective_date) rn
16 from test
17 )
18 select item_no, effective_date
19 from temp
20 where ( height <> lheight
21 or rn = 1
22 )
23 and item_no in (select item_no from temp
24 group by item_no
25 having count(distinct height) > 1
26 )
27 order by item_no, effective_date;
ITEM_NO EFFECTIVE_
---------- ----------
1 01/01/1980
1 08/03/1986
1 06/18/2000
3 08/01/1986
3 09/01/1986
SQL>
您可以使用多个analytical function
来实现。
select item_no, effective_date
from
(select item_no,
effective_date,
Lag(height) over
(partition by item_no order by effective_date) as prev_height,
Count(distinct height) over
(partition by item_no) as cnt_height
From your_table)
Where cnt_height > 1
And (prev_height is null or height <> prev_height);
欢呼!!