0

我有一个存储过程,它返回一个组中的类别数据。现在的问题是我需要对一个组的类别数据求和并将其插入到一个类别的开头。例如:

Group   Category    X1  X2  X3  X4
========================================================
A       A1          1   1   1   1
----------------------------------------------------
A       A2          1   1   1   1
---------------------------------------------------
B       B1          1   1   1   1
----------------------------------------------------
B       B2          1   1   1   1
----------------------------------------------------

应显示为:

Group   Category    X1  X2  X3  X4
=======================================================
A           A       2   2   2   2
----------------------------------------------------
A           A1      1   1   1   1
----------------------------------------------------
A           A2      1   1   1   1
----------------------------------------------------
B           B       2   2   2   2
----------------------------------------------------
B           B1      1   1   1   1
----------------------------------------------------
B           B2      1   1   1   1
----------------------------------------------------

所有这些都需要在一个程序中完成。我不能使用临时表。

4

3 回答 3

3

您可以使用 GROUP BY ROLLUP() 执行多个级别的聚合,包括根本不聚合:

select
  grp,
  coalesce(cat,grp) cat,
  sum(x1),
  sum(x2),
  sum(x3),
  sum(x4)
from
  my_table
group by grp,
  rollup(cat)
order by
  grp,
  cat nulls first;

http://sqlfiddle.com/#!4/4d9c4/8

于 2013-05-30T07:19:20.093 回答
1

请试试:

select 
    * 
from YourTable
union all
select 
    "Group", "Group" as Category, 
    SUM(X1), 
    SUM(X2),
    SUM(X3),
    SUM(X4)
from YourTable
Group by "Group"
order by "Group", Category
于 2013-05-30T07:02:46.120 回答
0

我猜你只是想要类似的东西

SELECT *
  FROM (
    SELECT group, category, x1, x2, x3, x4
      FROM your_table
    UNION ALL
    SELECT group, group, sum(x1), sum(x2), sum(x3), sum(x4)
      FROM your_table
     GROUP BY group
    )
 ORDER BY group, category

当然,您需要使用实际的列名——“GROUP is a reserved word so you cannot have a column namedGROUP”。

于 2013-05-30T07:02:12.247 回答