如何在同一列上聚合?

时间:2015-06-22 23:07:30

标签: database oracle aggregation

我想弄清楚哪个看起来非常简单,但我无法找到一种方法来做同样的事情。

考虑以下表和数据,

create table dummy_query 
(id varchar2(20), amount number(10,2), memo varchar(20));

insert into dummy_query values('1', 10.00, 'Memo');

insert into dummy_query values('1', 20.00, 'Memo1');

我希望将值设为:

Id MemoValue  Memo1Value TotalSum

----------

1   10.00       20.00       30.00

有没有办法以这种方式获取数据?

谢谢!

3 个答案:

答案 0 :(得分:1)

SQL Fiddle

Oracle 11g R2架构设置

create table dummy_query (id, amount, memo) AS
           SELECT '1', 10.00, 'Memo'  FROM DUAL
UNION ALL  SELECT '1', 20.00, 'Memo1' FROM DUAL
UNION ALL  SELECT '1', 30.00, 'Memo2' FROM DUAL;

查询1

如果TotalSum是所有备忘金额的总和(而不只是MemoMemo1),那么您可以这样做:

SELECT ID,
       SUM( CASE memo WHEN 'Memo'  THEN amount END ) AS MemoValue,
       SUM( CASE memo WHEN 'Memo1' THEN amount END ) AS Memo1Value,
       SUM( amount ) AS TotalSum
FROM   dummy_query
GROUP BY id

<强> Results

| ID | MEMOVALUE | MEMO1VALUE | TOTALSUM |
|----|-----------|------------|----------|
|  1 |        10 |         20 |       60 |

查询2

但是如果TotalSum只是MemoValue + Memo1Value,那么添加一个where子句:

SELECT ID,
       SUM( CASE memo WHEN 'Memo'  THEN amount END ) AS MemoValue,
       SUM( CASE memo WHEN 'Memo1' THEN amount END ) AS Memo1Value,
       SUM( amount ) AS TotalSum
FROM   dummy_query
WHERE  memo IN ( 'Memo', 'Memo1' )
GROUP BY id

<强> Results

| ID | MEMOVALUE | MEMO1VALUE | TOTALSUM |
|----|-----------|------------|----------|
|  1 |        10 |         20 |       30 |

查询3

或者,如果您因其他原因需要包含所有行,那么您可以这样做:

SELECT ID,
       SUM( CASE memo WHEN 'Memo'  THEN amount END ) AS MemoValue,
       SUM( CASE memo WHEN 'Memo1' THEN amount END ) AS Memo1Value,
       SUM( CASE WHEN memo IN ( 'Memo', 'Memo1' ) THEN amount END ) AS TotalSum
FROM   dummy_query
GROUP BY id

<强> Results

| ID | MEMOVALUE | MEMO1VALUE | TOTALSUM |
|----|-----------|------------|----------|
|  1 |        10 |         20 |       30 |

答案 1 :(得分:0)

我对PIVOT不是很熟悉,但你尝试了我确实在那里建立了查询。希望这是你需要的 -

SELECT a.*, b.SUM_AMT
  FROM ((SELECT ID, amount, memo FROM dummy_query) PIVOT (SUM (amount)
                                                   FOR (memo)
                                                   IN ('Memo', 'Memo1'))) a,
       (  SELECT ID, SUM (AMOUNT) "SUM_AMT"
            FROM dummy_query
        GROUP BY id) b
 WHERE a.id = b.id

可以有更好的方法来重新开始,让我们看看其他人必须分享的内容。

答案 2 :(得分:0)

已启动pivot的解决方案:

select id, memo, memo1, memo+memo1 msum from ( 
    select * from dummy_query 
    pivot (sum(amount) for (memo) in ('Memo' memo,'Memo1' memo1)))

更传统,没有支点:

select id, memo, memo1, memo1+memo msum from (
  select id, 
    sum(case when memo='Memo' then amount end) memo, 
    sum(case when memo='Memo1' then amount end) memo1
  from dummy_query group by id)

SQLFiddle