SQL插入每个维度值不存在的所有记录

时间:2018-05-29 09:29:56

标签: sql hana

我想将某个年份尚未存在的每个id插入到同一个表中,目标可以在下面看到:

ID  YearMonth

1   201805
2   201805
1   201804
1   201803

应该是:

ID  YearMonth

    1   201805
    2   201805
    1   201804
    1   201803
    2   201803
    2   201804

有没有人知道如何使用SQL来完成这项工作?

非常感谢!

编辑:

我已经尝试过了:

select A."ID",B."YEARMONTH" FROM "1_TEST" A FULL OUTER JOIN 
(select "YEARMONTH" from "1_TEST" GROUP BY "YEARMONTH") B
ON A."YEARMONTH" != B."YEARMONTH"

但这会产生太多记录。

数据库是一个HANA系统。

2 个答案:

答案 0 :(得分:0)

 SELECT "ID","YEARMONTH" FROM (
 SELECT DISTINCT A."ID",B."YEARMONTH" FROM "1_TEST" A, (SELECT "YEARMONTH" FROM "1_TEST" GROUP BY "YEARMONTH") B )
 WHERE ("ID","YEARMONTH") NOT IN (SELECT "ID","YEARMONTH" FROM "1_TEST")

更新,更好的版本:

 SELECT "ID","YEARMONTH" FROM (
 SELECT A."ID",B."YEARMONTH" FROM (SELECT "ID" FROM "1_TEST" GROUP BY "ID") A, (SELECT "YEARMONTH" FROM "1_TEST" GROUP BY "YEARMONTH") B )
 WHERE ("ID","YEARMONTH") NOT IN (SELECT "ID","YEARMONTH" FROM "1_TEST")

答案 1 :(得分:0)

首先:列名为ID,因为它唯一标识表中的记录。由于表中有重复的ID,这些ID显然是另一个表的ID,因此应该这样命名。

无论如何,您希望在表格中找到的所有ID与您在表格中找到的所有月份相结合。那将是一个交叉连接:

select ids.id, yearmonths.yearmonth
from (select distinct id from mytable) ids
cross join (select distinct yearmonth from mytable) yearmonths;

(请注意:我在您的表中使用了不同的选项,因为您还没有向我们展示任何其他表。如果有一个包含唯一ID的父表,那么我宁愿使用它。 YearMonths;如果有YearMonth表,请使用它而不是从组合表中收集不同的值。)

但是,您说您不想只选择这些,但在表格中插入缺失的记录。

insert into mytable (id, yearmonth)
  select ids.id, yearmonths.yearmonth
  from (select distinct id from mytable) ids
  cross join (select distinct yearmonth from mytable) yearmonths
  except
  select id, yearmonth from mytable;

在HANA中,您可以将其缩短为:

upsert mytable
  select ids.id, yearmonths.yearmonth
  from (select distinct id from mytable) ids
  cross join (select distinct yearmonth from mytable) yearmonths;

这只会插入新行,因为所有选定的列都是表格主键的一部分。