SQL-DataCamp-Joining Data in SQL

2023-11-13

1. Introduction to Joins

1.1 Introduction to INNER JOIN (video)
1.2 INNER JOIN

PostgreSQL was mentioned in the slides but you’ll find that these joins and the material here applies to different forms of SQL as well.

Recall from the video the basic syntax for an INNER JOIN, here including all columns in both tables:

SELECT *
FROM left_table
INNER JOIN right_table
ON left_table.id = right_table.id;

You’ll start off with a SELECT statement and then build up to an inner join with the cities and countries tables.

Instruction 1:
Begin by selecting all columns from the cities table.

SELECT *
FROM cities;

Instruction 2:

  • Inner join the cities table on the left to the countries table on the right, keeping all of the fields in both tables.
  • You should match the tables on the country_code field in cities and the code field in countries.
  • Do not alias your tables here or in the next step. Using cities and countries is fine for now.
SELECT * 
FROM cities
-- 1. Inner join to countries
INNER JOIN countries
-- 2. Match on the country codes
ON cities.country_code = countries.code;

Instruction 3:
Modify the SELECT statement to keep only the name of the city, the name of the country, and the name of the region the country resides in.

Recall from our Intro to SQL course that you can alias fields using AS. Alias the name of the city AS city and the name of the country AS country.

-- 1. Select name fields (with alias) and region 
SELECT cities.name AS city, countries.name as country, region
FROM cities
INNER JOIN countries
ON cities.country_code = countries.code;
1.3 INNER JOIN (2)

Instead of writing the full table name, you can use table aliasing as a shortcut. For tables you also use AS to add the alias immediately after the table name with a space. Check out the aliasing of cities and countries below.

SELECT c1.name AS city, c2.name AS country
FROM cities AS c1
INNER JOIN countries AS c2
ON c1.country_code = c2.code;

Notice that to select a field in your query that appears in multiple tables, you’ll need to identify which table/table alias you’re referring to by using a . in your SELECT statement.

You’ll now explore a way to get data from both the countries and economies tables to examine the inflation rate for both 2010 and 2015.

Sometimes it’s easier to write SQL code out of order: you write the SELECT statement after you’ve done the JOIN.

Instruction

  • Join the tables countries (left) and economies (right) aliasing countries AS c and economies AS e.
  • Specify the field to match the tables ON.
  • From this join, SELECT:
    • c.code, aliased as country_code.
    • name, year, and inflation_rate, not aliased.
-- 3. Select fields with aliases
SELECT c.code AS country_code, c.name, e.year, e.inflation_rate
FROM countries AS c
-- 1. Join to economies (alias e)
INNER JOIN economies AS e
-- 2. Match on code
ON c.code= e.code;
1.4 INNER JOIN (3)

The ability to combine multiple joins in a single query is a powerful feature of SQL, e.g:

SELECT *
FROM left_table
INNER JOIN right_table
ON left_table.id = right_table.id
INNER JOIN another_table
ON left_table.id = another_table.id;

As you can see here it becomes tedious to continually write long table names in joins. This is when it becomes useful to alias each table using the first letter of its name (e.g. countries AS c)! It is standard practice to alias in this way and, if you choose to alias tables or are asked to specifically for an exercise in this course, you should follow this protocol.

Now, for each country, you want to get the country name, its region, and the fertility rate and unemployment rate for both 2010 and 2015.

Note that results should work throughout this course with or without table aliasing unless specified differently.

Instruction 1:

  • Inner join countries (left) and populations (right) on the code and country_code fields respectively.
  • Alias countries AS c and populations AS p.
  • Select code, name, and region from countries and also select year and fertility_rate from populations (5 fields in total).
-- 4. Select fields
SELECT c.code, name, region, year, fertility_rate
-- 1. From countries (alias as c)
FROM countries AS c
-- 2. Join with populations (as p)
INNER JOIN populations AS p
-- 3. Match on country code 
ON c.code = p.country_code;

Instruction 2:

  • Add an additional inner join with economies to your previous query by joining on code.
  • Include the unemployment_rate column that became available through joining with economies.
  • Note that year appears in both populations and economies, so you have to explicitly use e.year instead of year as you did before.
-- 6. Select fields
SELECT c.code, name, region, e.year, fertility_rate, unemployment_rate
-- 1. From countries (alias as c)
FROM countries AS c
-- 2. Join to populations (as p)
INNER JOIN populations AS p
-- 3. Match on country code
ON c.code = p.country_code
-- 4. Join to economies (as e)
INNER JOIN economies AS e
-- 5. Match on country code
ON c.code = e.code;

Instruction 3:

  • Scroll down the query result and take a look at the results for Albania from your previous query. Does something seem off to you?
  • The trouble with doing your last join on c.code = e.code and not also including year is that e.g. the 2010 value for fertility_rate is also paired with the 2015 value for unemployment_rate.
  • Fix your previous query: in your last ON clause, use AND to add an additional joining condition. In addition to joining on code in c and e, also join on year in e and p.
-- 6. Select fields
SELECT c.code, name, region, e.year, fertility_rate, unemployment_rate
-- 1. From countries (alias as c)
FROM countries AS c
-- 2. Join to populations (as p)
INNER JOIN populations AS p
-- 3. Match on country code
ON c.code = p.country_code
-- 4. Join to economies (as e)
INNER JOIN economies AS e
-- 5. Match on country code and year
ON c.code = e.code AND p.year = e.year;
1.5 INNER JOIN via USING (video)
1.6 Review INNER JOIN using ON

Why does the following code result in an error?

SELECT c.name AS country, l.name AS language
FROM countries AS c
INNER JOIN languages AS l;

INNER JOIN requires a specification of the key field (or fields) in each table.

1.7 INNER JOIN with USING

When joining tables with a common field name, e.g.

SELECT *
FROM countries
INNER JOIN economies
ON countries.code = economies.code

You can use USING as a shortcut:

SELECT *
FROM countries
INNER JOIN economies
USING(code)

You’ll now explore how this can be done with the countries and languages tables.

Instruction:

  • Inner join countries on the left and languages on the right with USING(code).
  • Select the fields corresponding to:
    • country name AS country,
    • continent name,
    • language name AS language, and
    • whether or not the language is official.

Remember to alias your tables using the first letter of their names.

-- 4. Select fields
SELECT c.name AS country, continent, l.name AS language, official
-- 1. From countries (alias as c)
FROM countries as c 
-- 2. Join to languages (as l)
INNER JOIN languages as l
-- 3. Match using code
USING(code)
1.8 Self-ish Joins, just in CASE (video)
1.9 Self-join

In this exercise, you’ll use the populations table to perform a self-join to calculate the percentage increase in population from 2010 to 2015 for each country code!

Since you’ll be joining the populations table to itself, you can alias populations as p1 and also populations as p2. This is good practice whenever you are aliasing and your tables have the same first letter. Note that you are required to alias the tables with self-joins.

Instruction 1:

  • Join populations with itself ON country_code.
  • Select the country_code from p1 and the size field from both p1 and p2. SQL won’t allow same-named fields, so alias p1.size as size2010 and p2.size as size2015.
-- 4. Select fields with aliases
SELECT p1.country_code, 
       p1.size AS size2010, 
       p2.size AS size2015
-- 1. From populations (alias as p1)
FROM populations AS p1
-- 2. Join to itself (alias as p2)
INNER JOIN populations AS p2
-- 3. Match on country code
ON p1.country_code = p2.country_code;

Instruction 2:
Notice from the result that for each country_code you have four entries laying out all combinations of 2010 and 2015.

Extend the ON in your query to include only those records where the p1.year (2010) matches with p2.year - 5 (2015 - 5 = 2010). This will omit the three entries per country_code that you aren’t interested in.

-- 5. Select fields with aliases
SELECT p1.country_code,
       p1.size AS size2010,
       p2.size AS size2015
-- 1. From populations (alias as p1)
FROM populations AS p1
-- 2. Join to itself (alias as p2)
INNER JOIN populations AS p2
-- 3. Match on country code
ON p1.country_code = p2.country_code
-- 4. and year (with calculation)
AND p1.year = p2.year - 5;

Instruction 3:
As you just saw, you can also use SQL to calculate values like p2.year - 5 for you. With two fields like size2010 and size2015, you may want to determine the percentage increase from one field to the next:

With two numeric fields A and B, the percentage growth from A to B can be calculated as (B−A)/A∗100.0.

Add a new field to SELECT, aliased as growth_perc, that calculates the percentage population growth from 2010 to 2015 for each country, using p2.size and p1.size.

SELECT p1.country_code,
       p1.size AS size2010, 
       p2.size AS size2015,
       -- 1. calculate growth_perc
       
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

SQL-DataCamp-Joining Data in SQL 的相关文章

  • 包含列和行总计的 SQL 数据透视表

    我正在尝试将行和列总计添加到该数据透视表中 create table test4 city nvarchar 10 race nvarchar 30 sex nvarchar 10 age int insert into test4 val
  • 带有可变 WHERE 子句的批量 UPDATE 表

    我有一堆值对 foo1 bar1 foo2 bar2 我想做一堆更新 将 foo 列设置为 foo1 其中 bar 列为 bar1 我正在使用 psycopg2 在 Python 中执行此操作 我可以executemany与查询UPDATE
  • 更好地理解 SQL Server 中的架构

    就像标题一样 我还是一个SQLServer菜鸟 当我创建表 Mytable 时 数据库中显示 dbo Mytable 但有人能让我更好地理解模式吗 另外 在 Server 2008 TSQL 一书中 Itzik 说 在你的数据库中 表属于模
  • 时间序列数据的自连接

    我需要一些帮助来完成我认为应该是相当简单的自连接查询 只需要将两条记录中匹配的开始时间和结束时间合并为一条记录 假设我的表中有以下内容 Time Event 08 00 Start 09 00 Stop 10 30 Start 10 45
  • 获取mysql中逗号分隔行中不同值的计数

    一个表 Jobs 有 2 列 JobId 城市 当我们保存工作时 工作位置可能是多个城市 如下所示 JobId City 1 New York 2 New York Ohio Virginia 3 New York Virginia 我如何
  • 更改mysql数据库表中的日期格式

    大家早上好 只是一个简单的问题 在我现有的 MySql 数据库中 我几乎没有包含日期 的列 目前这些是年 月 日格式 但现在我需要将其全部更改为年 月 日格式 我试过了select date format curdate d m Y 但它不
  • meta_query,如何使用关系 OR 和 AND 进行搜索?

    已解决 请参阅下面的答案 我有一个名为的自定义帖子类型BOOKS 它有几个自定义字段 名称为 TITLE AUTHOR GENRE RATING 我该如何修复我的meta query下面的代码以便仅books在自定义字段中包含搜索词 tit
  • SQL Server使用in关键字传递字符串数组查询

    我认为 IN 子句不能接受具有多个值的绑定参数 Oracle 不能 需要几分钟 查询是 declare setting varchar max set setting Sales Entry Grid Cursor Customer Man
  • 处理与不同相关实体的一对多的正确模式

    我有一个 C 项目 我使用实体框架作为 ORM 我有一个User 可以向多家银行付款 每家银行都是一个独立的实体 并且每家银行都由不同的字段描述 问题是 一User可以没有或有很多不同的Banks 我不太确定如何对此进行建模 临时解决方案是
  • SQL:如何从一个表中获取另一个表中每一行的随机行数

    我有两个数据不相关的表 对于表 A 中的每一行 我想要例如表 B 中的 3 个随机行 使用光标这相当容易 但速度非常慢 那么我该如何用单个语句来表达这一点以避免 RBAR 呢 要获得 0 到 N 1 之间的随机数 可以使用 abs chec
  • MySQL“列计数与第 1 行的值计数不匹配”是什么意思

    这是我收到的消息 ER WRONG VALUE COUNT ON ROW 列计数与第 1 行的值计数不匹配 这是我的全部代码 我的错误在哪里 DROP TABLE student CREATE TABLE employee emp id I
  • SQL Server 中离线索引重建和在线索引重建有什么区别?

    重建索引时 有一个选项ONLINE OFF and ONLINE ON 我知道当ONLINE模式打开时 它会复制索引 切换新查询以利用它 然后重建原始索引 使用版本控制跟踪两者的更改 如果我错了 请纠正我 但是 SQL 在离线模式下会做什么
  • 需要在 SQL Server 中透视字符串值

    我有一个包含值的表 描述为 Occupation String Name String Developer A Developer B Designer X Coder Y Coder Z 我需要数据透视格式的值 Designer Deve
  • 总和和不同不会改变结果?

    我是一个新手 试图在这里解决这个问题 到目前为止还没有运气 非常感谢任何帮助 Select Distinct AB agency no ab branch no AS AGENCY BRANCH count AB agency no ab
  • 多边形内的 SQL 地理点在 STIntersect 上不返回 true(但使用 Geometry 返回 true)

    我不想仅仅为了在 STIntersect 中返回 true 而将地理数据转换为几何图形 下面是 SQL 中的代码 DECLARE point GEOGRAPHY GEOGRAPHY Point 1 1 4326 DECLARE polygo
  • MySQL NOT IN 来自同一个表中的另一列

    我想运行 mysql 查询来选择表中的所有行films其中的值title该列不存在于另一列的所有值中的任何位置 collection 这是我的表格的简化版本 其中包含内容 mysql gt select from films id titl
  • hive - 在值范围之间将一行拆分为多行

    我在下面有一张表 想按从开始列到结束列的范围拆分行 即 id 和 value 应该对开始和结束之间的每个值重复 包括两者 id value start end 1 5 1 4 2 8 5 9 所需输出 id value current
  • SQL Server:如果存在会大大减慢查询速度

    正在使用SQL Server 2012 我找到了一些关于查询优化的主题 并将 EXISTS 与 COUNT 进行比较 但我找不到这个确切的问题 我有一个看起来像这样的查询 select from tblAccount as acc join
  • CONTAINS 不适用于 Oracle Text

    我在执行此查询时遇到问题 SELECT FROM gob attachment WHERE CONTAINS gob a document java gt 0 它给了我 ORA 29902 error in executing ODCIIn
  • 如何使用 SQL 查询创建逗号分隔的列表?

    我有 3 个表 名为 应用程序 ID 名称 资源 id 名称 应用程序资源 id app id resource id 我想在 GUI 上显示所有资源名称的表格 在每一行的一个单元格中 我想列出该资源的所有应用程序 以逗号分隔 所以问题是

随机推荐

  • 不安全的加密算法

    不安全的加密算法 SKIPJACK RC4 RSA 1024位以下 des md2 md4 md5 属于经过验证 安全的 公开的加密算法 RSA DSA ECDSA 加入盐值的SHA256 推荐使用的数字签名算法有 DSA ECDSA
  • 值得重点推荐的BI软件有哪些?全在这里了

    在数字化程度越来越高的趋势下 发挥着推动企业数字化转型重要作用的商业智能BI也在不断提升市场份额 也催生出不少的BI软件新星 那么 BI软件有哪些 哪些BI软件更普遍适用于不同行业 针对这些问题 我们做了以下总结 BI软件有哪些 国内比较老
  • goland missing dependency错误

    新建一个项目 里面引用到第三方的包 项目编译没有问题 可是在goland里按住ctrl 鼠标点击打算跳转到第三方包相应的实现时却跳转不了 import的第三方也标红 同时go mod文件该第三方包也是标红的 看这篇文章 出现的问题和我的比较
  • moviepy音视频开发:音频拼接函数concatenate_audioclips介绍

    前往老猿Python博文目录 concatenate audioclips函数用于将多个音频剪辑进行拼接合成一个顺序播放的剪辑 调用语法 concatenate audioclips clips 说明 clips参数用于存放需要顺序拼接的音
  • 【备忘】Linux上传文件,下载文件

    背景小故事 这次在迁移服务器的时候要把ssl文件传到Linux里面 但是我又不想用ide来传 之前看同事演示过 当时没记住 感觉他简单操作就可以了 这次打算学会它 这功能用得不多 平常都不怎么使用 我们也可以用客户端连接服务器进行上传 方法
  • Android 设备 设置adb自动监听tcp 5555端口,重启有效

    Android 设备调试有两种连线方式 有线和无线 有线是通过USB导线连接android设备和电脑端 无线方式是通过连接WIFI 通过TCP的方式 连接设备和电脑端 一般用 5555端口 有线的调节 只需要打开调试模式基本就可以了 无线连
  • VirtualBox 安装32位Windows 7和64位Windows Sever 2008R2 双系统图文教程——利用VHD技术

    VirtualBox 安装32位Windows 7和64位Windows Sever 2008R2 双系统图文教程 利用VHD技术 先说说为什么要装双系统 因为想用一个系统只是用来休闲娱乐上网 聊天 看视频等等 所以这个时候坚决抵制一切数据
  • 【问题解决记录】无法识别的标志“-sdlMode”,在“p2”中

    问题解决记录 无法识别的标志 sdlMode 在 p2 中 参考文章 1 问题解决记录 无法识别的标志 sdlMode 在 p2 中 2 https www cnblogs com dbylk p 5133739 html 3 https
  • 30天自制操作系统第4天harib01a

    30天自制操作系统 第4天 C语言与画面显示的练习 用C语言实现内存写入 harib01a harib01a 准备材料 windows环境 VMware Workstation Visual Studio Code 程序和源代码 https
  • 如何为你的网站添加二级域名?

    一般公司注册的域名支持添加20个二级域名 辅助域名的添加与www的主域名相同 填写二级域名的名称 如bbs 并填写二级域名对应的IP 如果你的域名是www 98yun com bbs 这是一个论坛 你想添加一个bbs 98yun com 这
  • 大数据之——Zookeeper个人讲解

    一 zookeeper的概念 1 ZooKeeper是一个分布式的 开放源码的分布式应用程序协调服务 是Google的Chubby一个开源的实现 是Hadoop和Hbase的重要组件 它是一个为分布式应用提供一致性服务的软件 提供的功能包括
  • 用IDEA编写第一个JAVA程序

    第一步 打开IDEA IDEA下载链接 IntelliJ IDEA The Capable Ergonomic Java IDE by JetBrains 第二步 选择新建一个空项目 第三步 java项目的文件层次是 项目 包 类 创建一个
  • 6.2小车循迹,跟随,摇头测距功能实现

    1 循迹小车 1循迹模块的使用 TCRT5000传感器的红外发射二极管不断发射红外线 当发射出的红外线没有被反射回来或被反射回来但强度不够大时 红外接收管一直处于关断状态 此时模块的输出端为高电平 指示二极管一直处于熄灭状态 被检测物体出现
  • <1> linux与shell的关系

    在正式学习shell命令之前 如果你还对linux与shell的关系不甚了解 请耐心看完这篇简介 本文简要梳理了操作系统 shell的关系和作用 一个完整的计算机 整体结构如下图 我们的计算机由硬件组成 包括CPU 内存 主板 磁盘 各种外
  • 防关联软件技术分析之跨境电商防关联云服务器之超级VPS管理器

    众所周知 亚马逊有一个非常坑爹的规定 那就是同一个人或企业只能运营一个账号 并采用严格的程序对此进行监控 如果发现账户关联 则存在封号的风险 这就意味着 在同一个外网IP环境下操作多个账号是非常危险的 然而 我相信很多卖家手里都会有多个亚马
  • Java IO流

    Java的IO通过java io包下的类和接口来支持 在java io包下主要包括输入流 输出流两种IO流 每种输入 输出流又可分为字节流和字符流两大类 其中字节流以字节为单位来处理输入 输出操作 而字符流则以字符来处理输入 输出操作 1
  • java IO框架分析

    jave io框架 2010 11 10 22 18 34 分类 默认分类 举报 字号 订阅 可从IO的类层次 IO框架的设计模式来论述 总体来说 IO可以分为字节流和字符流 不同在于字符流由字节流包装而来 在IO读入之后经过JVM处理 把
  • 编译语言、解释语言与脚本语言之间的区别

    资料一 1 解释型语言与编译型语言的区别翻译时间的不同 编译型语言在程序执行之前 有一个单独的编译过程 将程序翻译成机器语言 以后执行这个程序的时候 就不用再进行翻译了 解释型语言 是在运行的时候将程序翻译成机器语言 所以运行速度相对于编译
  • 通俗易懂的机器学习——筛选垃圾邮件(贝叶斯分类)

    筛选垃圾邮件 贝叶斯分类 背景及应用 贝叶斯公式 数据集 引入依赖包 数据预处理 全局变量 过滤所有非中文词语 读取邮件 加载邮件 获取概率表 划分训练集和测试集 计算分词的概率表 保存概率表 检查邮件是否为垃圾文件 获取分词对应的概率字典
  • SQL-DataCamp-Joining Data in SQL

    1 Introduction to Joins 1 1 Introduction to INNER JOIN video 1 2 INNER JOIN PostgreSQL was mentioned in the slides but y