sql - 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)
。但我需要创建一个额外的表或列。
也许有人有一个好主意如何处理这个问题?
解决方案
使用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;
推荐阅读
- java - Spring Maven 项目结构 pom.xml
- regex - Spring MongoDB 数据元素匹配简单
- javascript - AngularJS:ng-repeat 和作用域 ng-click
- javascript - react-native:更新 setstate 数组中的元素不会重新渲染组件
- cmake - 如何将命令附加到编译器/链接器/归档命令
- swift - 创建播放器类导致错误“调用中的参数‘编码器’缺少参数”
- api - 聊天 API 自动添加和删除成员
- javascript - Sparkline Jquery - 有什么方法可以理解这一点以实际准确显示?
- sql - 将 varchar 转换为十进制的算术溢出错误
- .net - 从 IdentityServer4 获取 id_token?