Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Example tables and desired result: The result table shown below is the output I actually want.

1

tried the following query with pivot:

with pivot_data AS
(
  select client_id
        ,ph_type
        ,Ph_number
  from client_table
    inner join phone_table
      on client_table.phone_id = phone_table.ph_id
)
select *
from pivot_data
pivot (sum(ph_number)
       for ph_type in ('c','w','h')
      );

Result I got:

2

Any help would be appreciated. Answers in sql server would be great but oracle & mysql is also welcome if they can point me in the right direction. :)
Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
252 views
Welcome To Ask or Share your Answers For Others

1 Answer

Oracle Query:

SELECT *
FROM   (
  SELECT client_id, priority, phone_number, phone_type
  FROM   client_table c
         LEFT OUTER JOIN
         phone_table p
         ON ( c.phone_id = p.phone_id )
)
PIVOT ( MAX( phone_type ) AS phonetype, MAX( phone_number ) AS phonenumber
        FOR priority IN ( 1 AS Prio1, 2 AS Prio2, 3 AS Prio3 ) );

Output:

 CLIENT_ID PRIO1_PHONETYPE PRIO1_PHONENUMBER PRIO2_PHONETYPE PRIO2_PHONENUMBER PRIO3_PHONETYPE PRIO3_PHONENUMBER
---------- --------------- ----------------- --------------- ----------------- --------------- -----------------
         1 C               9999999999        H               5555555555        W               7777777777        

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...