我试图通过php从日期列表中获取平均天数,但我在网上找不到任何内容,所以我想我会在这里试试。以下是我目前为我输出的msyql。
2016-01-28
2016-01-27
2016-01-20
2015-12-28
2015-12-12
2015-12-05
2015-12-01
2015-11-27
2015-11-21
2015-11-11
2015-11-03
2015-10-31
2015-10-27
2015-10-17
2015-10-05
2015-09-20
2015-09-14
2015-09-02
2015-08-26
2015-08-18
2015-08-14
2015-08-08
2015-07-29
2015-07-18
2015-07-08
2015-06-22
2015-06-18
2015-06-07
2015-05-15
2015-05-13
2015-05-12
2015-05-02
我的代码来获取日期:
$result = mysql_query($query,$db) or die(mysql_error());
while($row = mysql_fetch_array($result)) {
echo $row['date']."<br>";
}
我正在尝试获得每次输出之间的平均天数....非常感谢我能获得的任何帮助!
答案 0 :(得分:0)
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table
(dt DATE NOT NULL PRIMARY KEY);
INSERT INTO my_table VALUES
('2016-01-28'),
('2016-01-27'),
('2016-01-20'),
('2015-12-28'),
('2015-12-12'),
('2015-12-05'),
('2015-12-01'),
('2015-11-27'),
('2015-11-21'),
('2015-11-11'),
('2015-11-03'),
('2015-10-31'),
('2015-10-27'),
('2015-10-17'),
('2015-10-05'),
('2015-09-20'),
('2015-09-14'),
('2015-09-02'),
('2015-08-26'),
('2015-08-18'),
('2015-08-14'),
('2015-08-08'),
('2015-07-29'),
('2015-07-18'),
('2015-07-08'),
('2015-06-22'),
('2015-06-18'),
('2015-06-07'),
('2015-05-15'),
('2015-05-13'),
('2015-05-12'),
('2015-05-02');
SELECT x.*
, DATEDIFF(MIN(y.dt),x.dt) diff
FROM my_table x
JOIN my_table y
ON y.dt > x.dt
GROUP
BY x.dt;
+------------+------+
| dt | diff |
+------------+------+
| 2015-05-02 | 10 |
| 2015-05-12 | 1 |
| 2015-05-13 | 2 |
| 2015-05-15 | 23 |
| 2015-06-07 | 11 |
| 2015-06-18 | 4 |
| 2015-06-22 | 16 |
| 2015-07-08 | 10 |
| 2015-07-18 | 11 |
| 2015-07-29 | 10 |
| 2015-08-08 | 6 |
| 2015-08-14 | 4 |
| 2015-08-18 | 8 |
| 2015-08-26 | 7 |
| 2015-09-02 | 12 |
| 2015-09-14 | 6 |
| 2015-09-20 | 15 |
| 2015-10-05 | 12 |
| 2015-10-17 | 10 |
| 2015-10-27 | 4 |
| 2015-10-31 | 3 |
| 2015-11-03 | 8 |
| 2015-11-11 | 10 |
| 2015-11-21 | 6 |
| 2015-11-27 | 4 |
| 2015-12-01 | 4 |
| 2015-12-05 | 7 |
| 2015-12-12 | 16 |
| 2015-12-28 | 23 |
| 2016-01-20 | 7 |
| 2016-01-27 | 1 |
+------------+------+
那么平均值就是差异的平均值,所以:
SELECT AVG(diff)
FROM
( SELECT x.*
, DATEDIFF(MIN(y.dt),x.dt) diff
FROM my_table x
JOIN my_table y
ON y.dt > x.dt
GROUP
BY x.dt
) a;
+-----------+
| AVG(diff) |
+-----------+
| 8.7419 |
+-----------+