If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

 
Go Back  dBforums > Database Server Software > DB2 > Creating one record out of multiple

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 04-09-09, 14:40
PKPChuck PKPChuck is offline
Registered User
 
Join Date: Sep 2006
Location: Columbus, OH
Posts: 64
Creating one record out of multiple

Trying to figure out easiest SQL to turn multiple records into 1 record


TABLE A

Name Keyword Value
Ted,City,New York
Ted,Job,Doctor
Ted,Hobby,Biking

need to convert

Name City Job Hobby
Ted New York Doctor Biking


Charlie
Reply With Quote
  #2 (permalink)  
Old 04-09-09, 15:13
ARWinner ARWinner is offline
Registered User
 
Join Date: Jan 2003
Posts: 3,575
with t1 (name) as (select distinct name from tablea) select t1.name,(select value from tablea as a where a.name = t1.name and a.keyword = 'City') as city,(select value from tablea as a where a.name = t1.name and a.keyword = 'Job') as Job,(select value from tablea as a where a.name = t1.name and a.keyword = 'Hobby') as hobby from t1

Andy
Reply With Quote
  #3 (permalink)  
Old 04-09-09, 18:46
tonkuma tonkuma is offline
Registered User
 
Join Date: Feb 2008
Location: Japan
Posts: 2,193
This must be one of repetiting questions in many forums.

Solutions are:
1) Self join, if maximum number of rows to be combined was fixed.
2) XMLAGG.
3) Recursive query.

Here is an answer(variation of Andy's):
Code:
------------------------------ Commands Entered ------------------------------
WITH
 /* Sample Data */
table_a(Name, Keyword, Value) AS (VALUES
 ('Ted', 'City',  'New York')
,('Ted', 'Job',   'Doctor')
,('Ted', 'Hobby', 'Biking')
) /* End of Sample Data */

SELECT a1.name || ' ' || a1.value || ' ' || a2.value || ' ' || a3.value
         AS "Combined result"
  FROM table_a a1
  LEFT JOIN
       table_a a2
   ON  a2.name = a1.name
   AND a2.keyword = 'Job'
  LEFT JOIN
       table_a a3
   ON  a3.name = a1.name
   AND a3.keyword = 'Hobby'
 WHERE a1.keyword = 'City'
;
------------------------------------------------------------------------------

Combined result               
------------------------------
Ted New York Doctor Biking    

  1 record(s) selected.
Reply With Quote
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On