簡體   English   中英

具有新列的多個表的UNION查詢

[英]UNION Query on Multiple Tables with New Columns

我只是想說這個論壇在我目前的工作中確實對我有很大幫助。

在為我們的ms訪問數據庫編寫sql查詢時,我需要其他幫助。 想法是對所有表(1月至12月)進行聯合查詢,以獲取唯一的ID號,並每月獲得其“ Item”值作為輸出表中的列。

可以在下面看到一個例子。 如果在表中找不到ID,則該值將返回null。

這在excel中似乎很容易做到,但我們希望在后端進行。 我只為所有表寫下了UNION查詢,但這就是我得到的結果。

先謝謝您的幫助。

表1:一月

 |    ID    |   Item    |
 |    1     |   Apple   |
 |    2     |   Salad   |
 |    3     |   Grapes  |  

表2:2月

 |    ID    |   Item    |
 |    1     |   Apple   |
 |    2     |   Grapes  |
 |    4     |   Grapes  |

輸出表:

 |    ID    |   January   |   February   |
 |    1     |    Apple    |   Apple      |
 |    2     |    Salad    |   Grapes     |
 |    3     |    Grapes   |   NULL       |
 |    4     |    NULL     |   Grapes     |

一種方法是與union all group by合並並group by

select id, max(January) as January, max(February) as February
from (select id, item as January, NULL as February from January
      union all
      select id, NULL, item from February
     ) jf
group by id;

如果id每個表僅存在一次,為什么不使用內部聯接呢? 如果該列不存在於另一個表中但存在於第一個表中,它將自動使該列無效

SELECT id, Jan.Item,Feb.Item 
FROM January Jan
INNER JOIN February Feb
on Jan.id=Feb.id

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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