QUERY#1
SELECT id,letter,IFNULL(date,dt) date FROM mytable,
(SELECT DATE(mindate + INTERVAL (secdiff/2) SECOND) dt
FROM (SELECT mindate,UNIX_TIMESTAMP(maxdate)
- UNIX_TIMESTAMP(mindate) secdiff
FROM (SELECT MIN(date) mindate FROM mytable) N,
(SELECT MAX(date) maxdate FROM mytable) X) AA) A;
樣本數據
mysql> DROP TABLE IF EXISTS mytable;
Query OK, 0 rows affected (0.00 sec)
mysql> CREATE TABLE mytable
-> (
-> id int not null auto_increment,
-> letter char(1),
-> `date` date,
-> primary key (id)
->);
Query OK, 0 rows affected (0.07 sec)
mysql> INSERT INTO mytable (letter,date) VALUES
-> ('A','2012-01-01'),('B',NULL),('C',NULL),('D','2012-01-15');
Query OK, 4 rows affected (0.00 sec)
Records: 4 Duplicates: 0 Warnings: 0
mysql> SELECT * FROM mytable;
+----+--------+------------+
| id | letter | date |
+----+--------+------------+
| 1 | A | 2012-01-01 |
| 2 | B | NULL |
| 3 | C | NULL |
| 4 | D | 2012-01-15 |
+----+--------+------------+
4 rows in set (0.00 sec)
mysql>
QUERY#1中執行
mysql> SELECT id,letter,IFNULL(date,dt) date FROM mytable,
-> (SELECT DATE(mindate + INTERVAL (secdiff/2) SECOND) dt
-> FROM (SELECT mindate,UNIX_TIMESTAMP(maxdate)
-> - UNIX_TIMESTAMP(mindate) secdiff
-> FROM (SELECT MIN(date) mindate FROM mytable) N,
-> (SELECT MAX(date) maxdate FROM mytable) X) AA) A;
+----+--------+------------+
| id | letter | date |
+----+--------+------------+
| 1 | A | 2012-01-01 |
| 2 | B | 2012-01-08 |
| 3 | C | 2012-01-08 |
| 4 | D | 2012-01-15 |
+----+--------+------------+
4 rows in set (0.00 sec)
mysql>
QUERY#2(清潔版)
此查詢使用UNIX時間戳記的平均值。如果所有的日期是NULL,它使用今天的日期:
SELECT id,letter,IFNULL(date,dt) date FROM mytable,
(
SELECT IF(K=0,DATE(NOW()),avgdt) dt FROM
(SELECT DATE(FROM_UNIXTIME(AVG(UNIX_TIMESTAMP(date))))
avgdt FROM mytable) AA,
(SELECT COUNT(date) K FROM mytable) BB
) A;
QUERY#2中執行
mysql> SELECT id,letter,IFNULL(date,dt) date FROM mytable,
-> (
-> SELECT IF(K=0,DATE(NOW()),avgdt) dt FROM
-> (SELECT DATE(FROM_UNIXTIME(AVG(UNIX_TIMESTAMP(date))))
-> avgdt FROM mytable) AA,
-> (SELECT COUNT(date) K FROM mytable) BB
->) A;
+----+--------+------------+
| id | letter | date |
+----+--------+------------+
| 1 | A | 2012-01-01 |
| 2 | B | 2012-01-08 |
| 3 | C | 2012-01-08 |
| 4 | D | 2012-01-15 |
+----+--------+------------+
4 rows in set (0.05 sec)
mysql>
試試看!
看看第一組數據,如果你有其他的記錄,像'5,E,NULL','6,F,2012-01-20',會是怎樣的結果呢? – 2013-03-22 18:05:12
*你爲什麼要操縱數據?檢索記錄時應該進行此計算。 – Kermit 2013-03-22 18:05:32
什麼是記錄的順序和字段的值之間的相關性(即會一直爲B在時間之前)? – 2013-03-22 18:07:50