2014-11-14 34 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