繁体   English   中英

SQL将两张表合并为一张表并添加一个新列

[英]SQL combine two tables into one table and add a new column

我需要将两张表合二为一。 Ans 另外,在 SQL 上向新表添加一列(分配一个 int 值)。 这样 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

任何帮助,将不胜感激。

尚不完全清楚您想要什么,但我假设这是一个 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM