[英]mysql join two rows with same column value and calculate certain column values and return all rows in one row
I have a table name agents_commission
have columns id, agent_id, deal_id, commission, deal_date. 我有一个表名称
agents_commission
包含列id,agent_id,deal_id,佣金,deal_date。
I want to select agent_id
, commission
from agents_commission
where month( date_deal
) = '$month' and year( date_deal
) ='$year'; 我想选择
agent_id
,从agents_commission
中选择commission
,其中month( date_deal
)='$ month'和year( date_deal
)='$ year';
but if the table have some rows have the same agent_id
join the same rows in one row and calculate the commission
values like row 66666.7 + 100000 as in row 1, 2 但是如果表中的某些行具有相同的
agent_id
则将同一行连接到同一行中,并像第1、2行一样计算commission
值,例如第66666.7 + 100000行
to be the final fetch_assoc as 成为最终的fetch_assoc作为
array('agent_id'=>1, 'commision'=>166666.7); array('agent_id'=> 1,'commision'=> 166666.7);
thanks 谢谢
Try using group by and aggregation: 尝试使用分组依据和聚合:
select agentid, sum(commission) as commission
from agents_commission
where month(date_deal) = '$month' and year(date_deal) ='$year';
group by agentid
You can not select all when you want to group by only one column(agentid). 如果只想按一列(agentid)分组,则不能全部选择。 you can do something like below
你可以做下面的事情
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. GROUP BY子句中使用的SELECT语句只能用于包含列名,聚合函数,常量和表达式。
Refer https://dev.mysql.com/doc/refman/5.5/en/group-by-modifiers.html 参考https://dev.mysql.com/doc/refman/5.5/en/group-by-modifiers.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.