1

I'm trying to get the last net_insurance of seach policy and after that sum by type_money Someone can help me?

This is my table policies

  |ID| |POLICY_NUM|  
   1      1234        
   2      5678     
   3      3444    
   4      4577

This is my table insurances

  |ID|  |POLICY_ID| |NET_INSURANCE|     |TYPE_MONEY|
   1           1           300          1
   2           1           400          2
   3           1           100          1
   4           2           400          1
   5           2           800          2
   6           3           100          1
   7           3           400          2
   8           4           800          2
   9           2           900          1

I'm trying to get the last net_insurance of seach policy_id

  |ID|  |POLICY_ID|  |LAST_NET_INSURANCE| |TYPE_MONEY|
   3           1           100              1
   9           2           900              1
   7           3           400              2
   8           4           800              2

WHAT I REALLY WANT IS THIS

  |TYPE_MONEY| |total|
        1        1000  
        2        1200   

Here is my query

http://sqlfiddle.com/#!2/19fb8/6

Please somebody can help me with this?

I will really appreciate help

4

2 回答 2

1

试试这个:

SELECT type_money, sum(net_insurance) from insurances
WHERE id IN (
  SELECT max(id) FROM insurances
  GROUP BY policy_id
)
GROUP BY type_money

请记住,您问题中的输入数据与您的小提琴中的输入数据不同。

摆弄来自问题的数据:here

输出来自问题的数据:

| TYPE_MONEY | TOTAL |
|------------|-------|
|          1 |  1000 |
|          2 |  1200 |
于 2013-10-30T20:29:05.450 回答
0

使用分组最大技巧,然后将结果相加。

SELECT insurances.type_money, SUM(insurances.net_insurance)
FROM insurances
LEFT JOIN insurances maxhack
    ON insurances.policy_id = maxhack.policy_id
    AND insurances.id < maxhack.id
WHERE maxhack.id IS NULL
GROUP BY type_money

请参阅:http ://dev.mysql.com/doc/refman/5.0/en/example-maximum-column-group-row.html

于 2013-10-30T20:26:41.383 回答