[英]Join/Merge Multiple Table with same column name
I want to join three tables respectively from the below SQLFiddle我想分别从下面的 SQLFiddle 加入三个表
http://sqlfiddle.com/#!9/5dd558/4 http://sqlfiddle.com/#!9/5dd558/4
Now I want to create one table from this table based on date and Brand.现在我想根据日期和品牌从这张表中创建一张表。 Like, I want data in this manner
就像,我想要这种方式的数据
Date , Brand , Series , Table_1_Viewers , Table_2_Viewers , Table_2_Viewers日期、品牌、系列、 Table_1_Viewers 、 Table_2_Viewers 、 Table_2_Viewers
and if data is not matched on the table then the field should be nulled.如果表上的数据不匹配,则该字段应为空。
What I have done我做了什么
SELECT h.*,
a.`amazon_viewers` AS "Table_1_Viewers",
n.`views` AS "Table_2_Viewers",
FROM `Table-1` h
LEFT JOIN `Table-2` a
ON h.`date` = a.`date`
AND h.`brand` = a.`brand`
LEFT JOIN `Table-3` n
ON h.`date` = n.`date`
AND h.`brand` = n.`brand`
Obviously I am selecting data from table-1 so it will display brand column only from table-1 but how can I get all table's brand column name in one column and merge these tables.??显然我是从表 1 中选择数据,所以它只会显示表 1 中的品牌列,但是如何将所有表的品牌列名称放在一列中并合并这些表。?
The output I want...我想要的输出...
| Date | Brand | Series | Table_1_Viewers | Table_2_Viewers | Table_3_Viewers | |:----------:|:--------:|:--------------:|:---------------:|:---------------:|:---------------:| | 12/1/2018 | TEST | TEST_SERIES | 100 | | | | 10/15/2018 | MTV | GOT | 1000 | | 1000 | | 12/1/2018 | TEST | Viking | 485632 | 856325 | | | 12/1/2018 | TEST | Another Series | | 200 | | | 10/15/2018 | POGO | GOT | | 1000 | | | 7/1/2019 | No_Match | TEST_SERIES | | | 100 | | 12/1/2018 | TEST-5 | Viking | | | 953022 |
You can do union all
with aggregation :您可以使用聚合进行
union all
:
select t.Date, t.Brand, t.Series_name,
sum(case when table_view = 't1' then amazone_viewer else 0 end) as Table_1_Viewers,
. . .
from (select h.date, h.brand, h.series_name, h.amazone_viewer, 't1' as table_view
from `Table-1` h union all
select h1.date, h1.brand, h1.series, h1.viewes, 't2'
from `Table-2` h1 union all
. . .
) t
group by t.Date, t.Brand, t.Series_name;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.