首页 文章

mysql连接具有相同列值的两行并计算某些列值并返回一行中的所有行

提问于
浏览
0

我有一个表名 agents_commission 有列id,agent_id,deal_id,佣金,deal_date .

我想从 agents_commission 中选择 agent_idcommission ,其中月份( date_deal )= '$month'和年份( date_deal )= '$year';

但是如果表中有一些行具有相同的 agent_id 连接一行中的相同行并计算 commission 值,如行66666.7 100000,如行1,2

成为最终的fetch_assoc

array('agent_id'=> 1,'commision'=> 166666.7);

谢谢

2 回答

  • 2

    如果只想按一列(agentid)进行分组,则无法选择全部 . 你可以做类似下面的事情

    select agent_id, sum(commission) as commission from temp where MONTH(deal_date) = '09' and year(deal_date) ='2018' group by agent_id;
    

    The SELECT statement used in the GROUP BY clause can only be used contain column names, aggregate functions, constants and expressions.

    参考https://dev.mysql.com/doc/refman/5.5/en/group-by-modifiers.html

  • 2

    尝试使用group by和aggregation:

    select agentid, sum(commission) as commission
    from agents_commission
    where month(date_deal) = '$month' and year(date_deal) ='$year';
    group by agentid
    

相关问题