sqlite3 - Transpose rows to columns in SQLite -
i have data this:
i trying transform (using sqlite). in desired result, within each id, each start should on same row chronologically closest end. if id has start no end (like id=4), corresponding end, empty (as shown below).
i have tried this
select id, max( case when start_end = "start" date end) start, max(case when start_end = "end" date end ) end df group id but result this, wrong because id=5 have 1 row, when should have two:
id start end 1 2 1994-05-01 1996-11-04 2 4 1979-07-18 <na> 3 5 2010-10-01 2012-10-06 any appreciated
create table mytable( id integer not null primary key ,start_end varchar(5) not null ,date date not null ); insert mytable(id,start_end,date) values (2,'start','1994-05-01'); insert mytable(id,start_end,date) values (2,'end','1996-11-04'); insert mytable(id,start_end,date) values (4,'start','1979-07-18'); insert mytable(id,start_end,date) values (5,'start','2005-02-01'); insert mytable(id,start_end,date) values (5,'end','2009-09-17'); insert mytable(id,start_end,date) values (5,'start','2010-10-01'); insert mytable(id,start_end,date) values (5,'end','2012-10-06');
select s.id id, s.date 'start', min(e.date) 'end' -- earliest end date "same id&start" -- start dates (select id, date intable start_end='start' ) s left join -- keep start-only lines -- end dates (select id, date intable start_end='end' ) e on s.id = e.id , s.date < e.date -- not group s.id, s.date -- "same id&start" order s.id, s.date; -- ensure sequence - left join (to keep start-only line id "4") 2 on-the-fly tables, start dates , end dates.
- take minimal end date higher start date (same id, using
min()andgroup by. - order id, start date.
i tested on test table similar dump, has no "not null" , no "primary key". guess test table irrelevant; otherwise explain effect, please.
note:
internally 3 pairs of dates id 5 (those match end>start) found, forwarded lowest end (min(end)) each of 2 different combinations of id , start group id, start. line end>start end not being minimum therefor not returned. makes 2 lines start/end pairs desired.
output (with .headers on):
id|start|end 2|1994-05-01|1996-11-04 4|1979-07-18| 5|2005-02-01|2009-09-17 5|2010-10-01|2012-10-06 update: incorporate helpful comments @matbailie.


Comments
Post a Comment