我在MySQL中有一张桌子:
+-----------------+-------------+------+-----+---------------------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------------+-------------+------+-----+---------------------+-------+
| period_duration | datetime | NO | PRI | 0000-00-00 00:00:00 | |
| duration | varchar(6) | YES | | NULL | |
| sample | varchar(2) | YES | | NULL | |
| corner | varchar(10) | YES | | NULL | |
| country | varchar(60) | NO | PRI | | |
| roaming_partner | varchar(60) | NO | PRI | | |
| pdp_in_total | int(8) | YES | | NULL | |
| pdp_in_ok | int(8) | YES | | NULL | |
| pdp_in_not_ok | int(8) | YES | | NULL | |
| pdp_in_ok_rate | int(8) | YES | | NULL | |
+-----------------+-------------+------+-----+---------------------+-------+
此表每小时都会有新的插入内容,每period_duration
个roaming_partner
个不同{/ 1}}:
+---------------------+----------+--------+----------+---------+-----------------------+--------------+-----------+---------------+----------------+
| period_duration | duration | sample | corner | country | roaming_partner | pdp_in_total | pdp_in_ok | pdp_in_not_ok | pdp_in_ok_rate |
+---------------------+----------+--------+----------+---------+-----------------------+--------------+-----------+---------------+----------------+
| 2014-12-16 14:00:00 | 3600 | 1 | GPRS_OUT | USA | Operator1 | 796 | 787 | 9 | 99 |
| 2014-12-16 15:00:00 | 3600 | 1 | GPRS_OUT | USA | Operator1 | 1748 | 1706 | 42 | 98 |
| 2014-12-16 16:00:00 | 3600 | 1 | GPRS_OUT | USA | Operator1 | 7 | 7 | 0 | 100 |
" ok_rate"是一个百分率。
我需要创建一个SELECT
,其中会显示过去24次插入中的每个country
,roaming_partner
和pdp_in_ok_rate
,平均值为pdp_in_ok_rate
%从这些插入。
就像我希望我的SQL查询说: "这是表格中每个运算符的最后24次插入中的平均pdp_in_ok_rate。不是在整个表格中,而是从最后的表格开始。"
有人可以帮帮我吗?
答案 0 :(得分:0)
这样做你想要的吗?
select country, roaming_partner, avg(pd_in_ok_rate) as avgrate
from table t
where period_duration >= date_sub(now(), interval -1 day)
group by country, roaming_partner;
这并不能为您提供平均细节。如果您还想要详细信息,可以将其用作子查询
select t.*, cr.avgrate
from table t join
(select country, roaming_partner, avg(pd_in_ok_rate) as avgrate
from table t
where period_duration >= date_sub(now(), interval -1 day)
group by country, roaming_partner
) cr
on t.country = cr.country and t.roaming_partner = cr.roaming_partner
where period_duration >= date_sub(now(), interval -1 day);