sql - Combining rows without a unique identifier -
i use on developing way combine rows of data when rows don't contain unique identifiers other rows reference. there pri_key, trailing rows never reference key.
disclaimer: have no control on design of table. query i'm running against database of software we've purchased , have in production.
here's sample similar data i'm looking at:
pri_key | personid | type | reference | details | date_time 101 1 renewal #001 trans # 001 2014-04-01 09:30:00 102 1 b modify #001 expires 30d 2014-04-01 09:30:00 104 1 renewal #001 trans # 002 2014-04-01 09:30:00 105 1 b modify #001 expires 60d 2014-04-01 09:30:00 108 2 renewal #020 trans # 003 2014-04-21 14:30:00 109 2 b modify #020 expires 45d 2014-04-21 14:30:00 111 3 renewal #140 trans # 004 2014-05-11 12:30:00 112 3 b modify #140 expires 90d 2014-05-11 12:30:00
there hundreds more rows, personid's have 4 rows, others have 2. there's b type row following type row , that's i'm after. can surmise, pri_key increases 1 b type row, there gaps between pri_keys seen in sample. , b have exact same time stamp.
using sample above, here's i'd see:
pri_key | personid | type | reference | details | date_time | modify | expires 101 1 renewal #001 trans # 001 2014-04-01 09:30:00 modify #001 expires 30d 104 1 renewal #001 trans # 002 2014-04-01 09:30:00 modify #001 expires 60d 108 2 renewal #020 trans # 003 2014-04-21 14:30:00 modify #020 expires 45d 111 3 renewal #140 trans # 004 2014-05-11 12:30:00 modify #140 expires 90d
essentially, need "expires" information b type's details
roll type's row. however, i'm getting caught on peronid's have 2 sets of rows. when run various attempts @ join
statements, end doubled expires
column:
pri_key | personid | type | reference | details | date_time | modify | expires 101 1 renewal #001 trans # 001 2014-04-01 09:30:00 modify #001 expires 60d 104 1 renewal #001 trans # 002 2014-04-01 09:30:00 modify #001 expires 60d 108 2 renewal #020 trans # 003 2014-04-21 14:30:00 modify #020 expires 45d 111 3 renewal #140 trans # 004 2014-05-11 12:30:00 modify #140 expires 90d
i'm thinking need find way use pri_key
+1 increments advantage, i'm not sure that's best approach or how handle that. can make suggestions? i'm aware i've written here may make perfect sense me , no 1 else, please let me know if can clarify. thanks!
i've created sql fiddle sample data inserted if it's easier reference that.
the commented "and" clauses shouldn't necessary (if you've described correct) , may make things slower, can include them safe. without commented stuff, may considerably faster comparing based on type/person id, , don't have worry indexing columns:
select a.*, b.reference 'modify', b.details 'expires' my_table join my_table b on a.pri_key = b.pri_key - 1 -- , a.date_time = b.date_time -- , a.personid = b.personid -- , b.type = 'b' a.type = 'a'
do need "modify" column?
Comments
Post a Comment