【问题标题】:SQL combine two tables into one table and add a new columnSQL将两张表合并为一张表并添加一个新列
【发布时间】:2014-06-26 08:15:25
【问题描述】:

我需要将两张表合二为一。 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

任何帮助将不胜感激。

【问题讨论】:

  • 加倍努力。 (解释你想要做什么)

标签: sql sql-server sql-server-2008 windows-7 netezza


【解决方案1】:

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

【讨论】:

  • 请看我的更新,我需要做一些计算并将两个表合并为一个!
  • 您的示例包含使用 ** 的多个部分。 * 是 SQL 中的保留符号,不能这样使用,这可能是原因。为避免混淆,请发布您遇到该错误时使用的确切查询。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-04
相关资源
最近更新 更多