doujie7497 2019-08-11 22:55
浏览 48
已采纳

如何使用付费和未付费值按年度对数据进行分组

i have a MYSQL database where i want to sort the totals of both paind and unpaid amounts. The Query i used was :

SELECT DISTINCT 
YEAR( app_payments.created_at ) AS YEARS,
SUM( app_payments.amount ) AS Total,
app_users.serial,
app_payments.`status` AS payment_state 
FROM
app_payments
INNER JOIN app_users ON app_payments.created_by = app_users.serial 
WHERE
app_payments.created_by = 'd88faa' 
GROUP BY
YEAR ( app_payments.created_at ),
app_payments.status 

i got the results as:

2017    1995    d88faa  1
2018    1200    d88faa  1
2019    1250    d88faa  0
2019    4990    d88faa  1

Where 1 stands for PAID and 0 stand for UNPAID

in my php code, i tried to group the data into years

$Stats = array ();
while(!$this->EndofSeek()){
$result = $this->Row();
if($result->payment_state == 0 ){
 if(in_array($result->YEARS,$Stats)){
 array_replace($Stats,['y'=>$result->YEARS , 'b'=>$result->Total ]);
}else{ array_push($Stats,['y'=>$result->YEARS , 'a'=>0 , 'b'=>$result->Total ]);}
}else if($result->payment_state == 1){
 array_push($Stats,['y'=>$result->YEARS , 'a'=>$result->Total , 'b'=>0 ]);
}
 }
  return json_encode($Stats)

This returns the output:

[{"y":"2017","a":"1995","b":0},
{"y":"2018","a":"1200","b":0},
{"y":"2019","a":"4990","b":"1450"},
{"y":"2019","a":"4990","b":0}]

Where y is YEARS , a is PAID and b is UNPAID

What i seek to achieve is to group all the data to a particular year where i would have [{"y":"2017","a":"1995","b":0}, {"y":"2018","a":"1200","b":0}, {"y":"2019","a":"4990","b":"1450"}]

Without it duplicating the year but rather merging them into a single unit.

What do i need to do, and which code do i need to implement to achieve this.

  • 写回答

1条回答 默认 最新

  • doubeizhong5178 2019-08-11 23:53
    关注

    Do you just want conditional aggregation?

    SELECT YEAR(p.created_at) AS YEAR,
           SUM( CASE WHEN p.status = 0 THEN p.amount END) AS Total_0,
           SUM( CASE WHEN p.status = 1 THEN p.amount END) AS Total_1
    FROM app_payments p INNER JOIN
         app_users u
         ON p.created_by = u.serial 
    WHERE p.created_by = 'd88faa' 
    GROUP BY YEAR(p.created_at);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误