簡體   English   中英

加入/合並具有相同列名的多個表

[英]Join/Merge Multiple Table with same column name

我想分別從下面的 SQLFiddle 加入三個表

http://sqlfiddle.com/#!9/5dd558/4

現在我想根據日期和品牌從這張表中創建一張表。 就像,我想要這種方式的數據

日期品牌系列Table_1_ViewersTable_2_ViewersTable_2_Viewers

如果表上的數據不匹配,則該字段應為空。

我做了什么

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` 

顯然我是從表 1 中選擇數據,所以它只會顯示表 1 中的品牌列,但是如何將所有表的品牌列名稱放在一列中並合並這些表。?

我想要的輸出...

|    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     |

您可以使用聚合進行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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM