如何将两个查询合并为一个没有重复的结果集?

时间:2016-08-12 13:09:05

标签: sql h2

我有一个包含三列id,name,training_run_id,named_entity_id的表。 我想使用两个名称列但使用不同的type_id

进行结果集
id  f1   training_run_id id  f1    training_run_id
27  0.3    2             41  0.5    3
27  0.3    2             55  0.66   4
13  0.2    1             41  0.5    3
13  0.2    1             55  0.66   4

查询结果为:

id  f1  training_run_id id  f1   training_run_id
13  0.2   1             41  0.5    3
27  0.3   2             55  0.66   4

我想知道如何得到这个:

hr {
    width: 77%;
    float: left;
    margin-top: 10px;
}
 .adresse h1{
    text-align: left;
    margin: 0px;
   margin-top: 20px;
}

.adresse h2 {
    text-align: left;
    font-weight: 300;
    color: #3594cb;
  
}

2 个答案:

答案 0 :(得分:1)

一些假设(基于OP的评论):

  • 您的2个子查询始终具有匹配的行数
  • 行如何匹配是不重要的

如果以上情况属实,我认为您可以让每个子查询返回rownum,以便您可以加入以避免采用笛卡尔计划:

SELECT r1.id, r1.f1, r2.id, r2.f1 FROM
(
    SELECT rownum as rn, id, f1  from RESULT where TRAINING_RUN_ID IN (1,2) AND NAMED_ENTITY_ID = 13
    GROUP BY ID
) as r1
JOIN
(
    SELECT rownum as rn, id, f1 from RESULT where TRAINING_RUN_ID IN (3,4) AND NAMED_ENTITY_ID = 13
    GROUP BY ID
) as r2
ON r1.rn = r2.rn

修改

实际上,不太确定上述内容是否会正常运行,因为正如rownum function文档中所述,似乎rownum计算 之前 group by

  

要在订购和分组后获取行号,请使用子查询。

如果是这种情况,我认为这是正确的查询:

SELECT r1.id, r1.f1, r2.id, r2.f1 FROM
(
  select rownum() as rn, id, f1
  from (
    SELECT id, f1  from RESULT where TRAINING_RUN_ID IN (1,2) AND NAMED_ENTITY_ID = 13
    GROUP BY ID
  ) t
) as r1
JOIN
(
  select rownum() as rn, id, f1
  from (
    SELECT id, f1 from RESULT where TRAINING_RUN_ID IN (3,4) AND NAMED_ENTITY_ID = 13
    GROUP BY ID
  ) t
) as r2
ON r1.rn = r2.rn

答案 1 :(得分:0)

您可以使用Qualify Statement。我刚刚用你的代码创建了上面的表格。然后,您可以通过R1.ID对数据进行分区,将所有数据分成用户ID上的分区,然后按R2 ID降序排序,然后按Row_number()= 1限定语句,这将取最低的R2分区内的.ID号并删除其余结果

   SELECT r1.id, r1.f1, r2.id, r2.f1 FROM
        (
            SELECT id, f1  from RESULT where TRAINING_RUN_ID IN (1,2) AND NAMED_ENTITY_ID = 13
            GROUP BY ID
        ) as r1
        JOIN
        (
            SELECT id, f1 from RESULT where TRAINING_RUN_ID IN (3,4) AND NAMED_ENTITY_ID = 13
            GROUP BY ID
        ) as r2
    QUALIFY (ROW_NUMBER () OVER (PARTITION BY R1.ID ORDER BY R2.ID ASC)) = 1