SQL将两个表组合到一个表中并添加一个新列

问题描述 投票:0回答:1

我需要将两个表合并为一个。 Ans也在SQL上的新表中添加一列(赋值)。因此,table1中的行和table2中的行被赋予不同的值。

例,

   table1
   ID1  ID2  ID3 VALUE

   table2
   ID1  ID2  ID3  VALUE

   table3
   ID1  ID2  ID3  VALUE

我需要将table3和table2组合到一个新表中并添加一个新列

    table_new
    top_id  ID2  ID3 VALUE

这是Netezza SQL。

   INSERT INTO new_table
   SELECT *
   FROM 
   (
       SELECT * ,  **sum (table1.VALUE * table2.VALUE) AS new_value**
       FROM  table1 
       JOIN 
            table2 
       ON  table1.id1 = table2.id1
       GROUP BY table2.id2,  table2.id3    
   ) AS tt_a  # here, I need to add a new column to tt, call it as top_id and also assign an int 
              # value to it, such as 80
   UNION ALL
   SELECT *
   FROM 
   (
       SELECT * ,  **sum (table1.VALUE * table3.VALUE) AS new_value**
       FROM  table1 
       JOIN 
            table3 
       ON  table1.id1 = table3.id1
       GROUP BY table3.id2,  table3.id3   
   ) AS tt_b   # here, I need to add a new column to tt, call it as top_id and also assign an  
               # int value to it, such as 81
    **ORDER BY top_id** 

我收到了错误:

我是SQL新手。

  ERROR [HY000] ERROR:  0 : Functionality not implemented

任何帮助,将不胜感激。

sql sql-server sql-server-2008 windows-7 netezza
1个回答
0
投票

它并不完全清楚你想要什么,但我会假设它是UNION ALL的例子。

UNION ALL将组合2个或更多SELECT语句的结果集。它返回每个select语句中的所有行(即使该行存在于多个SELECT语句中)作为1个结果集。

例:

select '81' as top_id,id2,id3 from T1 group by id2,id3
UNION ALL
select '79' as top_id,id3,id400 from T1 group by id3, id400
UNION ALL
SELECT '80' as top_id,id2,id3
   FROM  table1 
   JOIN 
        table2 
   ON  table1.id1 = table2.id1
   GROUP BY table1.id2,  table2.id3  
;

每个select语句(此示例组合3)应该是一个有效的查询,并且应该返回具有相同数据类型的相同数量的列。

参考:http://www.techonthenet.com/sql/union_all.php

© www.soinside.com 2019 - 2024. All rights reserved.