gpt4 book ai didi

mysql - 如何获取最后一个值并对sql中的一组值求和?

转载 作者:行者123 更新时间:2023-11-29 00:24:20 24 4
gpt4 key购买 nike

我正在尝试获取每个保单的 net_insurance 的最后一个值并按 type_money 求和

|policies|
|id| |policy_num| |type_money|
1 1234 1
2 5678 1
3 3444 2
4 4577 2


|insurances|
|id| |policy_id| |net_insurance|
1 1 100
2 1 200
3 1 400
4 2 500
5 2 600
6 3 100
7 4 200

这里我试图获取最后一个值

semi result bedore to do the sum            

|policy_num| |type_money| |last_net_insurance|
1234 1 400
5678 1 600
3444 2 100
4577 2 200

在获得最后一个值后,我想通过 type_money 求和,这才是我真正需要的

 |type money|    |sum|
1 1000
2 300

我试过这个但是我不知道如何得到每个保单的最后一个net_insurance,也做一个sum

  select * from policies
inner join insurances ON (insurances.policy_id =policies.id)
group by policies.id

这是我正在执行此操作的页面

http://sqlfiddle.com/#!2/acd8e/3

最佳答案

这里是:

SELECT p.type_money, sum(i1.net_insurance) total FROM (
SELECT max(id) id FROM insurances
GROUP BY policy_id
) i2
JOIN insurances i1 USING (id)
JOIN policies p ON p.id = i1.policy_id
GROUP BY p.type_money

fiddle here .

顺便说一句,提供 fiddle 和添加示例查询的绝对+1 :)

关于mysql - 如何获取最后一个值并对sql中的一组值求和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19673409/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com