按指定数量的有序行进行分组
我的 MySQL 数据库中有这样的表:
---------------------------
|fid | price | date |
---------------------------
| 1 | 1.23 | 2011-08-11 |
| 1 | 1.43 | 2011-08-12 |
| 1 | 1.54 | 2011-08-13 |
| 1 | 1.29 | 2011-08-14 |
| 1 | 1.60 | 2011-08-15 |
| 1 | 1.80 | 2011-08-16 |
fid
- 这是产品 IDprice
- 这是指定日期产品的价格
我想计算产品fid=1
的平均价格。我想计算指定 fid
的前 n=3
行按日期排序的平均价格,然后计算按日期排序的另外 3 行的平均价格。
如何对前 3 行进行分组并计算平均值,然后对接下来的 3 行进行分组并计算平均值。在计算之前,我需要按日期对行进行排序,然后对 n 行进行分组。
如果n=3
这应该返回这样的结果:
--------------
|fid | price |
--------------
| 1 | 1.40 | 2011-08-11 -> 2011-08-13 - average price for 3 days
| 1 | 1.56 | 2011-08-14 -> 2011-08-16 - average price for 3 days
How can I create SQL Query to do suchcalculate?
提前致谢。
I have such table in my MySQL database:
---------------------------
|fid | price | date |
---------------------------
| 1 | 1.23 | 2011-08-11 |
| 1 | 1.43 | 2011-08-12 |
| 1 | 1.54 | 2011-08-13 |
| 1 | 1.29 | 2011-08-14 |
| 1 | 1.60 | 2011-08-15 |
| 1 | 1.80 | 2011-08-16 |
fid
- this is the product idprice
- this is the price of the product in specified day
I want to calculate average price of the product fid=1
. I want to calculate the average price of first n=3
rows ordered by date for specified fid
, and then calculate average price for another 3 rows ordered by date.
How can I group first 3 rows and calculate avg and then group next 3 rows and calculate avg. Before calculation I need to sort the rows by date and then group n
rows.
If n=3
this should return such result:
--------------
|fid | price |
--------------
| 1 | 1.40 | 2011-08-11 -> 2011-08-13 - average price for 3 days
| 1 | 1.56 | 2011-08-14 -> 2011-08-16 - average price for 3 days
How can I create SQL Query to do such calculations?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不幸的是,mysql 不提供像 oracle、mssql 和 postgres 那样的分析功能。所以你必须利用变量来实现你的目标。
Unluckily mysql doesn't offer analytic functions like oracle,mssql and postgres do. So you have to play with variables to reach your goal.
也许你可以使用
= 转换为秒,除以 3 天的秒,然后向下舍入
maybe you could use
= convert to secounds, divide by secounds for 3 days, and round down