-5

我想创建查询来总结 Table1,如下所示:

Table1:
+-----+------+-----+------+
|Col1 | Col2 |Col3 | Col4 |
|1    | 2    |3    |  1   |
|3    | 2    |1    |  1   |
|2    | 1    |3    |  1   |
+-----+------+-----+------+
Output:   
 +----+---+-----+-----+----+----+                    
 |    | 1 |  2  |  3  |  4 |  5 |    
 +----+---+-----+-----+----+----+
 |Col1| 1 |  2  |  3  |    |    |      
 |Col2| 1 |  4  |     |    |    |       
 |Col3| 1 |     |  6  |    |    |     
 |Col4| 3 |     |     |    |    |
 +----+---+-----+-----+----+----+                                     

我最好的方法是使用 TRANSFORM PIVOT。

4

1 回答 1

3

您将希望使用UNION ALL第一个 UNPIVOT 数据,然后应用 PIVOT/TRANSFORM:

transform sum(val)
select col
from
(
  SELECT 'Col1' as col, Col1 as Val
  FROM test
  union all
  SELECT 'Col2' as col, Col2 as Val
  FROM test
  union all
  SELECT 'Col3' as col, Col3 as Val
  FROM test
  union all
  SELECT 'Col4' as col, Col4 as Val
  FROM test
) src
group by col
pivot val;

UNION ALL 查询将多列col1,col2等转换为单列中的多行,然后您可以应用 TRANSFORM 函数。

注意:此查询在 MS Access 2010 中进行了测试,并返回了结果:

+------+---+---+---+
| col  | 1 | 2 | 3 |
+------+---+---+---+
| Col1 | 1 | 2 | 3 |
| Col2 | 1 | 4 |   |
| Col3 | 1 |   | 6 |
| Col4 | 3 |   |   |
+------+---+---+---+

编辑,根据您需要所有值出现的评论1-5,然后我建议使用这些小的更改。

首先,创建一个包含所有要显示的数字的表格:

create table numbers
(
  n number
);

insert into numbers values (1);
insert into numbers values (2);
insert into numbers values (3);
insert into numbers values (4);
insert into numbers values (5);

一旦你有了一个包含所有要显示的值的表,然后使用上面的 UNION ALL 查询创建一个单独的查询。下面的查询是我创建并用名称保存的,unpiv但您可以随意调用它:

SELECT 'Col1' as col, Col1 as Val 
FROM test
union all
SELECT 'Col2' as col, Col2 as Val
FROM test
union all
SELECT 'Col3' as col, Col3 as Val
FROM test
UNION ALL SELECT 'Col4' as col, Col4 as Val
FROM test;

获得结果的关键是为每一列创建一个所有数字的列表,因此您将使用如下内容:

SELECT col, val
from numbers, (select distinct col from unpiv);

这会生成每个列名称的笛卡尔结果以及您要显示的数字。最后,您采用上述查询并将其加入您的unpiv查询,以便您可以转换数据。最后的查询是:

transform sum(u.val)
select src.col
from
(
  SELECT col, val
  from numbers, (select distinct col from unpiv)
) src
left join unpiv u
  on src.col = u.col
  and src.val = u.val
group by src.col
pivot src.val;

在 MS Access 2010 中测试给出了结果:

+------+---+---+---+---+---+
| col  | 1 | 2 | 3 | 4 | 5 |
+------+---+---+---+---+---+
| Col1 | 1 | 2 | 3 |   |   |
| Col2 | 1 | 4 |   |   |   |
| Col3 | 1 |   | 6 |   |   |
| Col4 | 3 |   |   |   |   |
+------+---+---+---+---+---+
于 2013-05-15T22:07:02.893 回答