简体   繁体   English

mysql,php用多个用户标识每月计算平均值

[英]mysql, php calculate mean per month with multiple userid's

This is driving me crazy, I cant seam to manage this without massive amount of code, this is my sql table: 这让我发疯,如果没有大量代码,我将无法进行管理,这是我的sql表:

userid    date        orderValue
2       2012-01-01      2000
1       2012-01-01      3000
1       2012-01-01      5000
1       2012-01-02      5000
2       2012-01-02      8000
2       2012-01-02      8000

For each month I need to get the mean value per user from the first date ever intill the current month. 对于每个月,我需要从直到当前月份的第一个日期获取每个用户的平均值。

The output I'am looking for is something along the line of $orderArray[$month][$userid]['mean'] 我正在寻找的输出类似于$ orderArray [$ month] [$ userid] ['mean']

I don't relay need the code, jut need to get my mind out the current thoughts that man stuck on. 我不需要中继代码,也不需要让我意识到这个人坚持的最新想法。 How would you go about solving this? 您将如何解决这个问题?

Something along the lines of: 类似于以下内容:

SELECT
  `userid`,
  DATE_FORMAT(`date`, '%Y%m') AS `month`,
  AVG(`orderValue`) AS `mean`
FROM
  `orderTable`
GROUP BY
  `userid`,
  `month`

Note that I'm using DATE_FORMAT instead of MONTH . 请注意,我使用的是DATE_FORMAT而不是MONTH If you don't do this, January 2012 and January 2013 would effectively be merged, which I guess is not what you want. 如果您不这样做,2012年1月和2013年1月将被有效合并,我想这不是您想要的。

You'll have to create the desired result array yourself in PHP by iterating over the SQL result set and putting each mean value in the appropriate place. 您必须在PHP中自己创建所需的结果数组,方法是遍历SQL结果集并将每个平均值放在适当的位置。

Try this :: 尝试这个 ::

    Select
    userid,
    SUM(ordervalue)/count(*) as mean

    from table 
    group by 

   userid

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM