SQL: How to create two fields based on same field from another table?

不想你离开。 提交于 2019-12-11 05:27:17

问题


I am sure this is quite easy to find, but through my searching I have been unable to find a solution. I'm probably not looking for the right keywords, so hopefully someone can help me.

I have two tables and I am trying to run a select query that will create two new fields based on the same field from another table.

Example: Table1 contains two fields called AgencyCountryCode and ClientCountryCode so I need to create two new fields called AgencyCountryName and ClientCountryName. In Table2 I have a list of country codes and country names to match with.

I have used the below code to match the agency country code to the name, but I can't figure out how to do the same thing for client, using the same lookup table/field.

SELECT
...various other fields...
CountryList.[CountryName] AS AgencyCountryName, 
FROM BookingData 
INNER JOIN CountryList ON BookingData.[Agency Country Code] = CountryList.[CountryCode];

Can anyone please let me know how I can perform the same lookup on two different fields?

Many thanks in advance.


回答1:


You just need to add another JOIN:

SELECT     ...various other fields...
           ACL.[CountryName] AS AgencyCountryName, 
           CCL.[CountryName] AS ClientCountryName
FROM       BookingData BD
INNER JOIN CountryList ACL ON BD.[Agency Country Code] = ACL.[CountryCode]
INNER JOIN CountryList CCL ON BD.[Client Country Code] = CCL.[CountryCode]


来源:https://stackoverflow.com/questions/45169610/sql-how-to-create-two-fields-based-on-same-field-from-another-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!