我查询了以下表格结构。
ID Date Before value After value
1 2014-04-25 Win Loss
1 2014-04-30 Loss Win
1 2014-08-18 Win Loss
1 2014-08-27 Loss Remise
1 2014-09-05 Remise Loss
2 2014-05-25 Win Remise
2 2014-06-07 Remise Win
2 2014-06-20 Win Loss
作为我的select语句的输出,我想要以下结果:
ID Start_Date End_Date After value
1 start 2014-04-25 Win
1 2014-04-26 2014-04-30 Loss
1 2014-05-01 2014-08-18 Win
1 2014-08-19 2014-08-27 Loss
1 2014-08-28 2014-09-05 Remise
1 2014-09-06 current Loss
2 start 2014-05-25 Win
2 2014-05-26 2014-06-07 Remise
2 2014-06-08 2014-06-20 Win
2 2014-06-21 current Loss
当然,该表有1000条记录需要正确。我尝试了排名和加入,但没有运气。如果有下一行,我需要将此值检索为开始日期+1。
答案 0 :(得分:1)
此方法使用MySql内联变量来保留最后一个ID以及与下一条记录进行比较的最后日期。
SELECT
t.id,
IF( @LastID = t.id, @LastDate, 'start ' ) as StartDate,
IF( NOT t.date = t2.date, t.date, 'current ' ) as EndDate,
t.after_value,
@LastID := t.id as saveForNextLineID,
@LastDate := t.date + INTERVAL 1 day as saveForNextDate
from
the_table t
left join ( select id, max( date ) as date
from the_table
group by id ) t2
ON t.id = t2.id,
(select @LastID := 0, @LastDate := 'start ' ) sqlvars
order by
t.id,
t.date
答案 1 :(得分:0)
类似的东西:
select t1.id,
(select max(date) + interval '1' day
from the_table t2
where t2.date < t1.date
and t2.id = t1.id) as start_date,
t1.date as end_date,
t1.after_value
from the_table t1
order by t1.id, t1.date;
SQLFiddle:http://sqlfiddle.com/#!2/8905a/3
答案 2 :(得分:0)
在某些行之间进行读取,但您可以使用UNION手动添加开始日期和结束日期,例如:
select * from mytable
union
select DISTINCT ID,'2000-01-01' as `Date`,`Before value`,``After value` from mytable
union
select DISTINCT ID,NOW() as `Date`,`Before value`,``After value` from mytable
尝试在子选择中弹出这个并在其上运行分组代码。