我有两个meta键:us_points和agent_id
我需要对每个用户的代理ID相同的所有us_points值进行汇总。
这是我尝试过的:
$cuser = wp_get_current_user(); $a_id = $cuser->agent_id;
global $wpdb;
$result = $wpdb->get_col("SELECT sum(meta_value) FROM $wpdb->usermeta WHERE meta_key = 'us_points' AND agent_id = $a_id" );
echo $result[0];
如果我删除AND agent_id = $ a_id,它会显示网站上所有用户的总数,但是我只需要显示agent_id中公共/匹配的元密钥值的总和
我将不胜感激。
答案 0 :(得分:1)
尝试一下,它应该以agent_id元关键字为目标,然后在进行求和之前按相同的agent_id值对记录进行分组。
$result = $wpdb->get_col("SELECT sum(meta_value) FROM $wpdb->usermeta WHERE meta_key = 'us_points' GROUP BY meta_value HAVING 'meta_key' = 'agent_id'" );
答案 1 :(得分:0)
$users = get_users();
$agent_points = array();
foreach( $users as $user ) {
$agent_points[] = array(
'agent_id' => $user->agent_id,
'us_points' => $user->us_points,
);
}
$agent_points
应该在以下结构中:
Array
(
[0] => Array
(
[agent_id] => 1
[us_points] => 30
)
[1] => Array
(
[agent_id] => 4
[us_points] => 10
)
[2] => Array
(
[agent_id] => 4
[us_points] => 30
)
[3] => Array
(
[agent_id] => 1
[us_points] => 20
)
)
然后
$results= array();
foreach( $agent_points as $values ) {
foreach( $values as $key => $value ) {
if( 'agent_id' === $key ) {
$results[ $value ] += $values['us_points'];
}
}
}
$results
对中预期的agent_id => us_points
:
Array
(
[1] => 50
[4] => 40
)