I have two tables that look like this:
Table_X
id, cert_number, other random info
Table_Y
id, cert_number, type, name
The issue arises because I have different types in table y that all apply to a single result I want to return (ie: owner name, carrier name, destination name) that are based on the type.
Is there a way that I can combine those into a single result with owner_name, carrier_name, and destination_name?
I used CASE to correctly get the information into the result, but since I use the type field in the select statement, I get back 3 results for each cert_number.
Thanks in advance!
EDIT:
Here is some sample data. The actual SQL statement is incredibly long due to the large amount of parameters I am required to pass along and check for.
table_x
id | cert_number
1 123-XYZ
2 124-zyx
table_y
id | cert_number | type | name
1 123-XYZ owner bob
2 123-XYZ destination paul
3 124-zyx owner steve
4 123-xyz carrier george
5 124-zyx carrier mike
6 124-zyx destination dan
You can use an aggregate function with a CASE
expression:
select x.cert_number,
max(case when y.[type] = 'owner' then y.name end) owner_name,
max(case when y.[type] = 'carrier' then y.name end) carrier_name,
max(case when y.[type] = 'destination' then y.name end) destination_name
from table_x x
inner join table_y y
on x.cert_number = y.cert_number
group by x.cert_number;
Or you can join on your table with the type
multiple times:
select x.cert_number,
y1.name as owner_name,
y2.name as carrier_name,
y3.name as destination_name
from table_x x
left join table_y y1
on x.cert_number = y1.cert_number
and y1.type = 'owner'
left join table_y y2
on x.cert_number = y2.cert_number
and y2.type = 'carrier'
left join table_y y3
on x.cert_number = y3.cert_number
and y3.type = 'destination';
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.