首页 > 解决方案 > SQL,左连接表,如何只保留一个值?

问题描述

我想加入两张桌子。表1是这样的:

id      Date
a     01.01.2021
a     02.01.2021
a     03.01.2021
b     01.01.2021
b     02.01.2021
b     03.01.2021
c     01.01.2021
c     02.01.2021
c     03.01.2021

表2是这样的:

id  value 
a    12
a     8
b    50

作为最终结果,我想要一个这样的表:对于表 2 中的现有 id,相同 id 的值的总和应存储在表 1 的最后日期中。

   id       Date     Value_FINAL
   a     01.01.2021    0
   a     02.01.2021    0
   a     03.01.2021    20
   b     01.01.2021    0
   b     02.01.2021    0
   b     03.01.2021    50
   c     01.01.2021    0
   c     02.01.2021    0
   c     03.01.2021    0

我最初尝试使用左连接来连接这两个表,

with t3 as ( select id, sum(value) Value_FINAL from t2 group by id) 
            select t1.*, t3.value_FINAL from t1 left join t3 on t1.id = t3.id;

在此之后,我可以得到这个:

   id       Date     Value_FINAL
   a     01.01.2021    20
   a     02.01.2021    20
   a     03.01.2021    20
   b     01.01.2021    50
   b     02.01.2021    50
   b     03.01.2021    50
   c     01.01.2021    0
   c     02.01.2021    0
   c     03.01.2021    0

但是,这不是我想要的。有人可以帮忙吗?如何仅将值保留在我也在考虑使用的“value_FINAL”列中的最后一个日期中last_value(value) over (partition by id order by date)。但我需要创建一个额外的表或列。
也许有人有一个好主意如何处理这个问题?

标签: sqlleft-join

解决方案


使用row_number(). 一种方法是:

select t1.*,
       (case when row_number() over (partition by id order by date desc) = 1
             then (select coalesce(sum(t2.value), 0) from table2 t2 where t2.id = t1.id)
             else 0
        end) as value_final
from table1 t1;

推荐阅读