将表中的多行分组到列中

时间:2014-04-05 07:58:59

标签: sql oracle oracle11g

我有两张桌子如下。

表1

+------+------+------+------+
| Col1 | Col2 | Col3 | Col4 |
+------+------+------+------+
|    1 | 1.5  | 1.5  | 2.5  |
|    1 | 2.5  | 3.5  | 1.5  |
+------+------+------+------+

表2

+------+--------+
| Col1 |  Col2  |
+------+--------+
|    1 |  12345 |
|    1 | 678910 |
+------+--------+

我想要的结果如下。

+------+------+------+------+-------+--------+
| Col1 | Col2 | Col3 | Col4 | Col5  |  Col6  |
+------+------+------+------+-------+--------+
|    1 |    4 |    5 |    4 | 12345 | 678910 |
+------+------+------+------+-------+--------+

此处Col2,Col3和Col4是表1中Col2,3,4的值的汇总。表2中的行转换为结果中的列。

我使用Oracle 11G并尝试了PIVOT选项。但我无法汇总表1中第2,3,4栏的值。

Oracle中是否有可用的功能提供直接解决方案而无需任何肮脏的工作?

提前致谢。

4 个答案:

答案 0 :(得分:1)

由于您在第二个表中只有2个记录,因此简单分组和连接就可以了。 由于我没有表格,我使用的是CTE和内联视图

with cte1 as (
    select 1 as col1 , 1.5 as col2 , 1.5 as col3, 2.5 as col4 from dual
    union all
    select 1  , 2.5  , 3.5 , 1.5 fom dual
    ) ,
    cte2 as (
    select 1 as col1 , 12345 as col2  fom dual
    union all
    select 1,678910  fom dual )

    select* from( 
    (select col1,sum(col2) as col2 , sum(col3) as col3,sum(col4) as col4
       from cte1 group by col1) as x 
    inner join 
    (select col1  ,min(col2) as col5 ,max(col2) as col from cte2
    group by col1
    ) as y
    on x.col1=y.col1)

答案 1 :(得分:0)

with
mytab1 as (select col1, col2, col3, col4, 0 col5, 0 col6 from tab1),
mytab2 as
(
    select
        col1, 0 col2, 0 col3, 0 col4, "1_COL2" col5, "2_COL2" col6
    from
        (
            select
                row_number() over (partition by col1 order by rowid) rn, col1, col2
            from
                tab2
        )
    pivot
        (
            max(col2) col2
            for rn in (1, 2)
        )
)
select
    col1,
    sum(col2) col2,
    sum(col3) col3,
    sum(col4) col4,
    sum(col5) col5,
    sum(col6) col6
from
    (
        select * from mytab1 union all select * from mytab2
    )
group by
    col1

答案 2 :(得分:0)

您好您可以使用以下查询

with t1 (col1,col2,col3,col4)
as
(
select 1,1.5,1.5,2.5 from dual
union
select 1,2.5,3.5,1.5 from dual

 ),
 t2 (col1,col2)
 as
 (
 select 1,12345 from dual
 union
 select 1,678910 from dual
 )
select * from 
(
select col1
       ,max(decode(col2,12345,12345)) as co5
       ,max(decode(col2,678910,678910)) as col6

from t2
group by col1
) a
inner join
(
 select  col1,sum(col2) as col2,sum(col3) as col3,sum(col4) as col4
 from t1
 group by col1
 ) b
 on a.col1=b.col1

答案 3 :(得分:0)

仅转动第二张桌子。然后,您可以在table1之间的嵌套UNION ALL上执行GROUP BY(col5和col6对于后续group by为null)和pivoted table2(col2,col3,col4对于后续group by为null)。