1

我在名称为“Sometable”的表中有两列business_line(值X,Y)和business_segment(值X,Y,Z与business_line相同的X和Y)。我有另一列名为 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:ACE 的总和不必是 100%,因为 B 和 D 也存在

4

2 回答 2

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)
) 
于 2012-08-10T08:21:24.800 回答
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
于 2012-08-10T08:15:37.390 回答