分组前N行,但也需要对列值求和

时间:2014-06-07 20:30:06

标签: mysql sql

我使用以下查询对数据集中的前N行进行分组:

SELECT mgap_ska_id,mgap_ska_id_name, account_manager_id, 
mgap_growth AS growth,mgap_recovery,
(mgap_growth+mgap_recovery) total
  FROM
  (SELECT mgap_ska_id,mgap_ska_id_name, account_manager_id, mgap_growth,
  mgap_recovery,(mgap_growth+mgap_recovery) total,
    @acid_rank := IF(@current_acid = account_manager_id, @acid_rank + 1, 1) 
    AS acid_rank,
       @current_acid := account_manager_id 
       FROM mgap_orders
       ORDER BY account_manager_id, mgap_growth DESC 
     ) ranked
     WHERE acid_rank <= 5 

结果非常接近我的需要,但我遇到了一个我需要帮助的总问题。我附上了查询结果的屏幕截图(我不得不屏蔽客户名称和ID以保护隐私; mgap_ska_id和account_manager_id是INT列,mgap_ska_id_name是VARCHAR。

enter image description here

理论上我需要SUM(我知道它是一个聚合;这就是问题)多个mgap_growth值,同时保持排名。

如果我是GROUP BY,那么我将失去前5名。目前,mgap_growth值只是mgap_growth列中每mgb_ska_id的一个值;我需要它是每mgb_ska_id所有mgap_growth值的总和,并保持排名前五的排名。

谢谢!

1 个答案:

答案 0 :(得分:0)

您可以在选择字段中添加以下行:

(SELECT SUM(t.mgap_growth) FROM mgap_orders t WHERE t.mgap_ska_id = ranked.mgap_ska_id ) AS total_mgap_growth

所以你的代码将是:

SELECT mgap_ska_id,mgap_ska_id_name, account_manager_id, 
mgap_growth AS growth,mgap_recovery,
(mgap_growth+mgap_recovery) total,
(SELECT SUM(t.mgap_growth) FROM mgap_orders t WHERE t.mgap_ska_id = ranked.mgap_ska_id ) AS total_mgap_growth
  FROM
  (SELECT mgap_ska_id,mgap_ska_id_name, account_manager_id, mgap_growth,
  mgap_recovery,(mgap_growth+mgap_recovery) total,
    @acid_rank := IF(@current_acid = account_manager_id, @acid_rank + 1, 1) 
    AS acid_rank,
       @current_acid := account_manager_id 
       FROM mgap_orders
       ORDER BY account_manager_id, mgap_growth DESC 
     ) ranked
     WHERE acid_rank <= 5