SQL Server: Merge Data Rows in single table in output -
i have sql server table following fields , sample data:
id name address age 23052-pf peter timbuktu 25 23052-d1 jane paris 22 23052-d2 david london 24 23050-pf sam beijing 22 23051-pf nancy nyc 26 23051-d1 carson cali 22 23056-pf grace la 28 23056-d1 smith boston 23 23056-d2 mark adelaide 26 23056-d3 hose mexico 25 23056-d4 mandy victoria 24
each id -pf unique in table.
each id -dx related same id -pf.
each id -pf may have 0 or more ids -dx.
the maximum number of -dx rows given -pf 9.
i.e. id 11111-pf can have 11111-d1, 11111-d2, 11111-d3 11111-d9.
output expected above sample data:
id id (without suffix) pf_name pf_address pf_age d_name d_address d_age 23052-pf 23052 peter timbuktu 25 jane paris 22 23052-pf 23052 peter timbuktu 25 david london 24 23050-pf 23050 sam beijing 22 null null null 23051-pf 23051 nancy nyc 26 carson cali 22 23056-pf 23056 grace la 28 smith boston 23 23056-pf 23056 grace la 28 mark adelaide 26 23056-pf 23056 grace la 28 hose mexico 25 23056-pf 23056 grace la 28 mandy victoria 24
i need able join -pf , -dx above.
if -pf has 0 dx rows, d_name, d_address , d_age columns in output should return null.
if -pf has 1 or more dx rows, pf_name, pf_address , pf_age should repeat each row in output , d_name, d_address , d_age should contain values each related dx row.
need use mssql.
query should not use views or create additional tables.
thanks help!
select pf.id, pf.idnum, pf.name pf_name, pf.address pf_address, pf.age pf_age, dx.name d_name, dx.address d_address, dx.age d_age ( select id, left(id, 5) idnum, name, address, age mytable right(id, 3) = '-pf' ) pf left outer join ( select id, left(id, 5) idnum, name, address, age mytable right(id, 3) != '-pf' ) dx on pf.idnum = dx.idnum
sqlfiddle demo: http://sqlfiddle.com/#!6/dfdbb/1
Comments
Post a Comment