如何在Oracle中使用分组集重命名该列

时间:2019-04-10 16:04:25

标签: sql oracle grouping-sets

我使用分组集计算总金额

SELECT
CASE
    WHEN GROUPING(Name) = 1 THEN 'TOTAL' ELSE Name END,
ID,
SUM(Amount)   
FROM Table1 GROUP BY GROUPING SETS ( (ID, Name), (ID) );

我会得到这样的东西

ID      Name     Amount

11    company1    100
11    company1    200
11    TOTAL       300
22    company2    100
22    company2    200
22    TOTAL       300

但是我想将名称“ TOTAL”更改为“ comany1 -total”或“ company2-total” 例如

ID         Name         Amount

11      company1          100
11      company1          200
11      company1-TOTAL    300
22      company2          100
22      company2          200
22      company2-TOTAL   300

有可能这样做吗?我坚持了一段时间。谢谢!!!

3 个答案:

答案 0 :(得分:0)

您只需要一个子查询,如:

select A.ID, 
CASE WHEN ID = 11 AND A.Name = 'TOTAL' THEN 'company1-TOTAL' 
     WHEN ID = 22 AND A.Name = 'TOTAL' THEN 'company2-TOTAL'
ELSE A.Name
end as NewName
, A.Amount
from (
--BELOW IS YOUR QUERY
SELECT
CASE
    WHEN GROUPING(Name) = 1 THEN 'TOTAL' ELSE Name END,
ID,
SUM(Amount)   
FROM Table1 GROUP BY GROUPING SETS ( (ID, Name), (ID) ))A

答案 1 :(得分:0)

这将为您提供所需的分组设置:

with test_table as (
 select 11 ID, 'company1' Name, 100 Amount from dual union all
 select 11 ID, 'company1' Name, 200 Amount from dual union all
 select 22 ID, 'company2' Name, 100 Amount from dual union all
 select 22 ID, 'company2' Name, 200 Amount from dual
)

select id, name, amount from (
  SELECT

    ID,
    name,
    Amount

  FROM test_table
  union all
  select id, name || '-TOTAL', sum(amount) from test_table  group by id, name || '-TOTAL'
) order by id, name, amount
;

这是另一种方式:

{{1}}

答案 2 :(得分:0)

将其表述为:

SELECT (CASE WHEN GROUPING(Amount) = 1 THEN Name || '-TOTAL' ELSE Name END),
       ID, SUM(Amount)   
FROM Table1
GROUP BY GROUPING SETS ( (ID, Name, Amount), (ID, Name) );

这假设Amount是唯一的。如果没有,也许您还有另外一个可以使用的唯一列。