postgresql - Group records with multiple sets in sql -
i have optimize select query less no. of records when have same data different dates. need sort rows date , should combine rows single until finds different column value. typically data below.
date c_val 1/1/2016 200 2/1/2016 200 3/1/2016 300 4/1/2016 300 5/1/2016 300 6/1/2016 200 7/1/2016 200
then output should follows.
start_date end_date c_val 1/1/2016 2/1/2016 200 3/1/2016 5/1/2016 300 6/1/2016 7/1/2016 200
the query followed this:
select min(date) start_date, max(date) end_date, c_val t_ord group c_val;
but returning 2 records grouping c_val. think need additional on order , break when finds new value. there feature available in postgres?
you can use difference of row numbers approach classify consecutive rows (ordered date) same c_val 1 group , start on new group when new value encountered. after done, min
, max
date of each group per c_val.
select min(date) startdate,max(date) enddate,c_val (select c_val,date,row_number() over(order date) -row_number() over(partition c_val order date) grp t_ord ) t group c_val,grp;
Comments
Post a Comment