我有一张桌子
Recordid Price Start date end date
-----------------------------------------
1 20 2017-10-01 2017-10-02
2 20 2017-10-03 2017-10-04
3 30 2017-10-05 2017-10-05
4 20 2017-10-06 2017-10-07
我希望在它开始时和结束时获得所有价格,因此我的结果集将是
20. 2017-10-01. 2017-10-04
30. 2017-10-05. 2017-10-05
20. 2017-10-06. 2017-10-07
我有问题要弄清楚
它是一个Oracle数据库
答案 0 :(得分:1)
我用下面的代码弄明白了
SELECT distinct price
, case when start_dt is null then lag(start_dt) over (order by start_date)
else start_dt end realstart
, case when end_dt is null then lead(end_dt) over (order by end_date)
else end_dt end realend
FROM (SELECT case when nvl(lag(price) over (order by start_date),-1) <> price then start_date end start_dt
, case when nvl(lead(price) over (order by end_date),-1) <>price then end_date end end_dt
, price
, start_date
, end_date
FROM t) main
WHERE start_dt is not null
or end_dt is not null
答案 1 :(得分:0)
以下是一种可能适用于您的方法:
select price, min(start_date), max(end_date)
from (select t.*,
sum(case when prev_price = price and prev_end_date = start_date - 1
then 0 else 1
end) over (order by t.start_date) as grp
from (select t.*,
lag(t.end_date) over (order by t.start_date) as prev_end_date,
lag(t.price) over (order by t.start_date) as prev_price
from t
) t
) t
group by price, grp
答案 2 :(得分:0)
根据您的示例数据,我认为您希望每当价格按记录ID的顺序更改时都有开始日期和结束日期。 以下查询可能包含比必要更多的子查询,因为可读性。内部选择确定何时更改价格,称为组更改。来自该组的下一级别的滚动总和。这是可能的,因为只有组更改包含值&gt;其余的很明显。
// for example i =10
1) String.valueOf(i);//Now it will return "10"
2 String s=Integer.toString(i);//Now it will return "10"
3) StringBuilder string = string.append(i).toString();
//i = any integer nuber
4) String string = "" + i;
5) StringBuilder string = string.append(i).toString();
6) String million = String.format("%d", 1000000)
使用以下数据进行测试(请注意,我已经为您提供的示例数据添加了一些记录,因为我希望拥有一个包含三个记录的组)
SELECT GRP,
PRICE,
MIN("Start date") AS "Start date",
MAX("end date") AS "end date"
FROM ( SELECT sub.*,
SUM(GROUP_CHANGE) OVER (ORDER BY RECORDID) AS GRP
FROM ( SELECT t.*,
CASE
WHEN RECORDID = LAG(t.RECORDID) OVER (ORDER BY t.PRICE, t.RECORDID) + 1
THEN 0
ELSE RECORDID
END AS GROUP_CHANGE
FROM t ) sub ) fin
GROUP BY GRP, PRICE
ORDER BY GRP
GRP PRICE Start date end date
---------- ---------- ---------- --------
1 20 01.10.17 04.10.17
4 30 05.10.17 05.10.17
8 20 06.10.17 11.10.17