2014-11-14 33 views
0

我只想說,這個論壇在我目前的工作中真的幫了我很大忙。UNION查詢多列表與新列

我需要另一個幫助,爲我們的ms訪問數據庫編寫sql查詢。我們的想法是爲所有表(1月至12月)進行聯合查詢,以獲取唯一的ID號,並將每月的「Item」值作爲輸出表中的一列。

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

這似乎很容易在Excel中做,但我們想在我們的後端做到這一點。我只能寫下所有表的UNION查詢,但這是我得到的。

在此先感謝您的幫助。

表1:一月

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

表2:二月

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

輸出表:

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

回答

2

一種方法是用union allgroup 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; 
0

如果id每個表只存在一次,爲什麼不使用Inner Join呢?如果它不存在於另一個表上但是存在於第一個表上,則它將自動將該列空置。

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