Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
260 views
in Technique[技术] by (71.8m points)

mysql - Join 2 tables and display by id,priority & number

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

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

1 Reply

0 votes
by (71.8m points)

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        

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...