我正在尝试创建一个查询,将数据从一个表转移到另一个表,如下所述?

时间:2017-10-27 20:24:21

标签: mysql sql oracle

SELECT EL_VALUES_FIELD1
     , EL_VALUES_FIELD2
     , EL_VALUES_FIELD4
     , SUM (EL_VALUES_FIELD5) 
FROM DATA_FORM_VALUES_919906 
GROUP 
    BY EL_VALUES_FIELD1
     , EL_VALUES_FIELD2
     , EL_VALUES_FIELD4

图像1是源表,图像2是目标图像

source

destination

2 个答案:

答案 0 :(得分:0)

以下查询将完成工作:

select field1,
       field2,
       Group_concat(field3 order by field3 desc separator ',') as keyfield_3,
       field4,
       sum(amount) as amount
from table
group by field1,field2,field4;

以上查询仅适用于 MySQL ,仅显示结果。如果要将这些值插入另一个表中,请执行以下操作:

Insert into tablename(keyfield1,keyfield2,keyfield3,keyfield4,amount)
select field1,
           field2,
           Group_concat(field3 order by field3 desc separator ',') as keyfield_3,
           field4,
           sum(amount) as amount
    from table
    group by field1,field2,field4;

如果您想在Oracle中完成相同的任务,则应使用LISTAGG()代替Group_concat()

<强>甲骨文:

Insert into tablename(keyfield1,keyfield2,keyfield3,keyfield4,amount)
select field1,
           field2,
           LISTAGG(field3,',') WITHIN GROUP (order by field3 desc),
           field4,
           sum(amount) as amount
    from table
    group by field1,field2,field4;

答案 1 :(得分:0)

如果您正在使用MySQL,请使用GROUP_CONCAT来合并field3中的值。

INSERT INTO destination (keyfield1, keyfield2, keyfield3, keyfield4, amount)
SELECT field1, field2, GROUP_CONCAT(field3), field4, SUM(amount)
FROM source
GROUP BY field1, field2, field4

如果您实际使用的是Oracle,请参阅Is there any function in oracle similar to group_concat in mysql?