表格定义
Table 1 (horizontal) 这是一个用户表
Table 1 (horizontal) This is a table of users
| id | name | phone |
---------------------
| 1 | Bob | 800 |
| 2 | Phil | 800 |
Table 2 (Vertical Table) 这是一个团队表
Table 2 (Vertical Table) This is a table of teams
| id | name |
------------------
| 1 | Donkey |
| 2 | Cat |
Table 3 (Vertical Table) 此表连接前两个
Table 3 (Vertical Table) This table is connecting the first two
| id | user_id | team_id |
--------------------------
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 3 | 2 | 1 |
<小时>
我的目标
我希望能够以返回以下信息的方式查询数据:
I would like to be able to query the data in such a way that i get the following back:
| id | name | phone | Donkey | Cat |
-------------------------------------
| 1 | Bob | 800 | 1 | 1 |
| 2 | Phil | 800 | 1 | Null |
此表将包含我的水平表数据,然后是其他两个垂直表的组合以创建附加列.表 2 最终成为列名标题.并且行值作为布尔值从表三中提取.
This table would have my horizontal table data, then a combination of the other two vertical tables to create the appended columns. Where table 2 ends up being the column name headings. And the row valus are pulled from table three as a boolean.
您正在寻找数据透视表:
You're chasing a pivot table:
select u.*,
sum(case when t1.name = 'Donkey' then 1 else 0 end) Donkey,
sum(case when t1.name = 'Cat' then 1 else 0 end) Cat
from users u
inner join user_team ut1
on u.id = ut1.user_id
inner join teams t1
on ut1.team_id = t1.id
group by name
演示:http://sqlfiddle.com/#!9/5fd33/7
这篇关于将两个垂直表合并到一个水平表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
如何有效地使用窗口函数根据 N 个先前值来决定How to use windowing functions efficiently to decide next N number of rows based on N number of previous values(如何有效地使用窗口函数根据
在“GROUP BY"中重用选择表达式的结果;条款reuse the result of a select expression in the quot;GROUP BYquot; clause?(在“GROUP BY中重用选择表达式的结果;条款?)
Pyspark DataFrameWriter jdbc 函数的 ignore 选项是忽略整Does ignore option of Pyspark DataFrameWriter jdbc function ignore entire transaction or just offending rows?(Pyspark DataFrameWriter jdbc 函数的 ig
使用 INSERT INTO table ON DUPLICATE KEY 时出错,使用 Error while using INSERT INTO table ON DUPLICATE KEY, using a for loop array(使用 INSERT INTO table ON DUPLICATE KEY 时出错,使用 for 循环数组
pyspark mysql jdbc load 调用 o23.load 时发生错误 没有合pyspark mysql jdbc load An error occurred while calling o23.load No suitable driver(pyspark mysql jdbc load 调用 o23.load 时发生错误 没有合适的
如何将 Apache Spark 与 MySQL 集成以将数据库表作为How to integrate Apache Spark with MySQL for reading database tables as a spark dataframe?(如何将 Apache Spark 与 MySQL 集成以将数据库表作为