在一个小组内做一个小组

时间:2012-08-10 08:05:30

标签: sql oracle group-by

我在名称为“Sometable”的表中有两列business_line(值为X,Y)和business_segment(值X,Y,Z与X和Y相同,为business_line)。我有另一个名为type_of_payment的列(值为A,B,C,D,E)和名为transaction_value的最后一列。这就是我想要做的事情:

对按business_line和business_segment分组的交易进行求和,并找出这些付款中A,C,E的比例。所以我的输出表就是这样的

                                             (last three columns can be named anything
                                              but they specify proportions of A,C,E)  
Business_line       SUM(transaction_value)   A        C        E
and business seg.
X                   100                      20%      30%      50%
Y                   200                      11%      12%      77%     
X                   300                        and so on
Y                   170
Z                   230

我该怎么做?

PS:A C E的总和不必是100%,因为B和D也存在

2 个答案:

答案 0 :(得分:2)

这是标准的SQL,应该适用于Oracle(但未经测试):

SELECT
   business_line,
   business_segment,
   grand_total,
   A_total * 100.0 / grand_total as A,
   C_total * 100.0 / grand_total as C,
   E_total * 100.0 / grand_total as E
FROM
   (
       SELECT
          business_line,
          business_segment,
          SUM(transaction_value) as grand_total,
          SUM(CASE WHEN payment_type = 'A' THEN transaction_value END) as A_total,
          SUM(CASE WHEN payment_type = 'C' THEN transaction_value END) as C_total,
          SUM(CASE WHEN payment_type = 'E' THEN transaction_value END) as E_total
       FROM
          SomeTable
       GROUP BY
          business_line,
          business_segment
    ) as t

答案 1 :(得分:2)

对于Oracle 11g及更高版本,您可以使用PIVOT

select *
from
(
select sometable.line, paymenttype,total, 100.0*transaction_value/total as percentage
from sometable
    inner join
    (select line, sum(transaction_value) as total
        from sometable
        group by line) total
    on sometable.line = total.line          
) 
pivot 
(
    sum(percentage) for paymenttype in (a,c,e)
)