I need to pull data from two tables where two values match. The joining table produces 5 rows, and will always produce 5 rows.
Is there a way that I can take one column with distinct values and return multiple columns in a single row?
For an example: Table A: orig_zip, dest_zip, pri_mode
Table B: orig_zip, dest_zip, serv_comm
Table B will always return 5 results for every 1 result in Table A when doing an inner join like the following:
SELECT a.orig_zip, a.dest_zip, b.serv_comm, a.pri_mode
FROM A a
INNER JOIN B b
ON a.orig_zip = b.orig_zip and a.dest_zip = b.dest_zip
ORDER BY a.orig_zip, a.dest_zip, b.mail_class;
How can I take the 5 results, and turn them into a single row in oracle. The only field that is different in the results will be the serv_comm field.
The final row should have the following setup:
[ORIG_ZIP][DEST_ZIP][SERV_COMM1][SERV_COMM2][SERV_COMM3][SERV_COMM4][SERV_COMM5][PRI_MODE]
I did some research, and here is the answer on SQL Fiddle!
From 11g you can also do it with the PIVOT clause:
FROM trans_mode a
INNER JOIN servcomm b
ON a.orig_zip = b.orig_zip and a.dest_zip = b.dest_zip
pivot
(
max(serv_comm)
for (mail_class)
in ('PRI' AS pri_serv, 'FCM' AS fcm_serv, 'PER' AS per_serv, 'PKG' AS pkg_serv, 'STD' AS std_serv)
);
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.