简体   繁体   中英

Left Join tables but then get fancy with the columns - SQL

I have a database with 2 tables and I am trying to join them in a specific way.

Table 1: Profile

Columns: friend_ID, gender, birthyear, hometown, checkins

Table 2: Education

Columns: friend_ID, school_name, school_type

I want to left join like so:

    SELECT 
       friend_ID, birthyear, checkins 
   FROM Friend_Profile 
   LEFT JOIN 
       Education on Profile.friend_ID = Education.friend_ID

Then I want to change birthyear to age (2013-birthyear) and code school_type into categories. 3 for 'Graduate School', 2 for 'College', 1 for 'High School' and 0 for 'Other or no data' and just keep the highest number for each row. (The education table often contains multiple rows representing different school_type for the same friend_ID.

Any help is appreciated, Thanks.

Sorry for the delay. I created the tables and ran the statement on localhost.

Education Table: Screenshot

Profile Table: Screenshot

Result after running below SQL statement: Screenshot

SELECT profile.friend_id, birthyear, checkins, MAX( 
CASE WHEN school_type =  'High School'
THEN 1 
WHEN school_type =  'College'
THEN 2 
WHEN school_type =  'Graduate School'
THEN 3 
ELSE 0 
END ) AS school_type
FROM profile
LEFT JOIN education ON profile.friend_id = education.friend_ID
GROUP BY (
profile.friend_id
)

Update:

Use YEAR(CURDATE()) to get the current year (2014), or replace it with 2013, if you want to work with last year. You can obviously add more fields to grab if there are any missing in the select statement that you want to add.

Result: Screenshot

It shows 14 because I used YEAR(CURDATE()) instead of 2013. You can change that based on what you need.

SELECT profile.friend_id, YEAR(CURDATE()) - birthyear as age, checkins, MAX( 
CASE WHEN school_type =  'High School'
THEN 1 
WHEN school_type =  'College'
THEN 2 
WHEN school_type =  'Graduate School'
THEN 3 
ELSE 0 
END ) AS school_type
FROM profile
LEFT JOIN education ON profile.friend_id = education.friend_ID
GROUP BY (
profile.friend_id
)

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