如何在Oracle中将表中的两行合并为一行?

时间:2017-06-08 20:31:24

标签: sql oracle oracle12c

我有一个包含以下列和值的表。

Name Rate Kind NoOfItems TotalAmount
---- ---- ---- --------- -----------
ABC     1 O           50          50
ABC     2 A           10          20

(*)表将有N个名称,类型将为O或A

我必须将以下表格数据输出到每一个名称的单行中。

Name O_Rate A_Rate O_Items A_Items O_Amount A_Amount TotalItems TotalAmount
---- ------ ------ ------- ------- -------- -------- ---------- -----------
ABC       1      2      50      10       50       20         60          70

如何使用单个查询按预期输出转换上述表数据。我尝试过Case和Decode,但在这两种情况下我只得到两行。

提前致谢。

2 个答案:

答案 0 :(得分:2)

我喜欢使用条件聚合执行此操作,但您也可以使用select o.name, o.Rate as o_Rate, a.Rate as a_Rate, o.Kind as o_Kind, a.Kind as a_Kind, o.NoOfItems as o_NoOfItems, a.NoOfItems as a_NoOfItems, o.TotalAmount as o_TotalAmount, a.TotalAmount as a_TotalAmount, (o.NoOfItems + a.NoOfItems) as TotalItems, (o.TotalAmount + a.TotalAmount) as TotalAmount from t o join t a on o.name = a.name and o.rate = 'O' and a.rate = 'A';

=LEFT(CELL("filename"),FIND("[",CELL("filename"))-1)&"Concept2\"

答案 1 :(得分:2)

自Oracle 11.1(我认为)以来,您可以使用PIVOT运算符,如下所示。

更好:看起来你所谓的"输入"实际上是一个中间结果,是其他数据处理的输出。如果是这样,您可以将PIVOT操作与您正在进行的操作结合起来 - 没有理由将其作为单独的步骤,复制一些工作(以及一些执行时间)。如果你能展示你如何得到所谓的"输入"首先,我们可以向您展示如何将其与旋转相结合。

with
     test_data ( name, rate, kind, noofitems, totalamount ) as (
                 select 'ABC', 1, 'O', 50, 50 from dual
       union all select 'ABC', 2, 'A', 10, 20 from dual
     )
-- End of test data (not part of the solution).
-- SQL query begins BELOW THIS LINE.
select name, o_rate, a_rate, o_noofitems as o_items, a_noofitems as a_items,
       o_totalamount as o_amount, a_totalamount as a_amount,
       o_noofitems + a_noofitems as totalitems,
       o_totalamount + a_totalamount as totalamount
from   test_data
pivot(
       max(rate) as rate, max(noofitems) as noofitems, max(totalamount) as totalamount
       for kind in ('O' as o, 'A' as a)
     )
;

NAME  O_RATE  A_RATE  O_ITEMS  A_ITEMS  O_AMOUNT  A_AMOUNT  TOTALITEMS  TOTALAMOUNT
----  ------  ------  -------  -------  --------  --------  ----------  -----------
ABC        1       2       50       10        50        20          60           70