简体   繁体   中英

Generate SQL output in a specific format

There are two database tables. For example:

  1. User:-

    User ID Name
    1 Mr. A
    2 Mr. B
  2. Email Details:-

    Email ID User ID Email
    1 1 safk@as.com
    2 1 asdfk@ad.com
    3 2 wqe@sda.com

I want to generate the result using Oracle SQL query in the following format:-

|User ID | Name |  Email1    | Email2     |
| -------|------|------------|------------|
| 1      | Mr. A| safk@as.com|asdfk@ad.com|
| 2      | Mr. B| wqe@sda.com|            |

(A user may have any number of emails.)

_________ create table statements

create table Users(
  UserId int,
  Name varchar2(50)
);

create table emailDetails(
  EmailId int,
  UserId int,
  Email varchar2(50)
  );

insert into Users(UserId, Name) values (1, 'Mr A');
insert into Users(UserId, Name) values (2, 'Mr B');
insert into EmailDetails(EmailId, UserId, Email) values(1,1,'safk@as.com');
insert into EmailDetails(EmailId, UserId, Email) values(2,1,'asdfk@ad.com');
insert into EmailDetails(EmailId, UserId, Email) values(3,2,'wqe@sda.com');

if you are allowed to have one column called emails with a comma delimited list then you can use listagg. if you need a dynamic number of columns you will need to use dynamic sql.

here is the solution with one column called emails

SELECT
    u.userId, name,
    LISTAGG(email,', ') WITHIN GROUP(ORDER BY u.userId) AS emails
from users u 
join emaildetails e on(u.userId = e.Userid)
GROUP BY u.userId, name
ORDER BY u.userId;

you can run the fiddle here http://sqlfiddle.com/#!4/546eb/8

If you use the ROW_NUMBER analytic function, you can then use that in a subquery in combination with some grouping.

  SELECT u.userid,
         u.name,
         MIN (CASE WHEN e.email_num = 1 THEN e.email END)     AS email1,
         MIN (CASE WHEN e.email_num = 2 THEN e.email END)     AS email2
    FROM users u
         LEFT JOIN
         (SELECT userid,
                 email,
                 ROW_NUMBER () OVER (PARTITION BY userid ORDER BY emailid)     AS email_num
            FROM emailDetails) e
             ON (u.userid = e.userid)
GROUP BY u.userid, u.name;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM