在联合查询中包括具有字段名称的列

时间:2019-07-05 16:13:04

标签: sql ms-access ms-access-2010

我有一个具有访问权限的表,该表具有我的产品的所有条件,需要创建一个查询,以将有关条件的所有信息放在单个列中。为此,我使用了联合查询。现在,我想在其旁边的列上有一个条件的字段名称。

有可能得到这个结果吗?

对不起,我缺乏知识,无法以差劲的方式发表这篇文章,并感谢您为我提供的任何帮助。

我的表具有以下结构:

+------+--------------+--------------+--------------+-------------+
| P/N  |  Criteria 1  |  Criteria 2  |  Criteria 3  |  Criteria 4 |
+------+--------------+--------------+--------------+-------------+
| 12A  |  blue        |  plastic     |  Box         |  5mm        |
| 20C  |  neutral     |  metal       |  Pack        |  120mm      |
+------+--------------+--------------+--------------+-------------+

我在Access中有一个联合查询,结果如下:

+------+------------+
| P/N  |  Criteria  |
+------+------------+
| 12A  |    blue    |
| 12A  |    plastic |
| 12A  |    Box     |
| 12A  |    5mm     |
| 20C  |    neutral |
| 20C  |    metal   |
| 20C  |    pack    |
| 20C  |    120mm   |
+------+------------+

我想要的最终结果是这种格式的表格:

+------+-----------+----------------+
| P/N  |  Criteria |  Criteria Name |
+------+-----------+----------------+
| 12A  |  blue     |  Criteria 1    |
| 12A  |  plastic  |  Criteria 2    |
| 12A  |  Box      |  Criteria 3    |
| 12A  |  5mm      |  Criteria 4    |
| 20C  |  neutral  |  Criteria 1    |
| 20C  |  metal    |  Criteria 2    |
| 20C  |  pack     |  Criteria 3    |
| 20C  |  120mm    |  Criteria 4    |
+------+-----------+----------------+

1 个答案:

答案 0 :(得分:1)

假设您的联合查询看起来像这样-

select t.[p/n], t.[criteria 1] as criteria
from yourtable t
union all
select t.[p/n], t.[criteria 2] as criteria
from yourtable t
union all
select t.[p/n], t.[criteria 3] as criteria
from yourtable t
union all
select t.[p/n], t.[criteria 4] as criteria
from yourtable t

然后,您可以像这样添加字段名称:

select t.[p/n], t.[criteria 1] as criteria, 'Criteria 1' as [Criteria Name]
from yourtable t
union all
select t.[p/n], t.[criteria 2] as criteria, 'Criteria 2' as [Criteria Name]
from yourtable t
union all
select t.[p/n], t.[criteria 3] as criteria, 'Criteria 3' as [Criteria Name]
from yourtable t
union all
select t.[p/n], t.[criteria 4] as criteria, 'Criteria 4' as [Criteria Name]
from yourtable t