简体   繁体   English

左联接表,然后看中列-SQL

[英]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. 我有一个包含2个表的数据库,我正在尝试以一种特定的方式将它们加入。

Table 1: Profile 表1:简介

Columns: friend_ID, gender, birthyear, hometown, checkins 列:friend_ID,性别,出生年份,家乡,签到

Table 2: Education 表2:教育

Columns: friend_ID, school_name, school_type 列: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. 然后,我想将出生年份更改为年龄(2013-出生年份),并将school_type编码为类别。 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. “研究生院”为3个,“学院”为2个,“高中”为1个,“其他或无数据”为0,并且只保留每行最高的数字。 (The education table often contains multiple rows representing different school_type for the same friend_ID. (教育表通常包含多个行,这些行代表同一friend_ID的不同school_type。

Any help is appreciated, Thanks. 任何帮助表示赞赏,谢谢。

Sorry for the delay. 抱歉耽搁了。 I created the tables and ran the statement on localhost. 我创建了表并在localhost上运行了该语句。

Education Table: Screenshot 教育表: 屏幕截图

Profile Table: Screenshot 资料表: 截图

Result after running below SQL statement: Screenshot 在下面的SQL语句中运行后的结果: 屏幕截图

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. 使用YEAR(CURDATE())获取当前年份(2014),如果要使用去年,则将其替换为2013。 You can obviously add more fields to grab if there are any missing in the select statement that you want to add. 如果要添加的select语句中缺少任何字段,显然可以添加更多字段以进行抓取。

Result: Screenshot 结果: 屏幕截图

It shows 14 because I used YEAR(CURDATE()) instead of 2013. You can change that based on what you need. 它显示14,因为我使用YEAR(CURDATE())而不是2013。您可以根据需要进行更改。

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
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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