按行值分组的列总和

时间:2013-05-15 17:54:17

标签: sql ms-access

我想创建查询以总结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。

1 个答案:

答案 0 :(得分:3)

您首先要使用UNION ALL取消数据,然后应用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查询将多列col1col2等转换为单列中的多行,然后您可以应用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 |   |   |   |   |
+------+---+---+---+---+---+