Tuesday, February 9, 2010

Mysql sample find out the no order period > 2 hours

In one of my application, I need use sql to figure out any 2 hours period which does not have any order. 
DROP TABLE IF EXISTS TEMPORDER;

CREATE TABLE TEMPORDER (
ROWNUM INT NOT NULL,
CREATED_DATE DATETIME NOT NULL
);

INSERT INTO TEMPORDER VALUES(1, DATE(CONCAT(YEAR(CURRENT_DATE()), "-", MONTH(CURRENT_DATE()), "-", DAY(CURRENT_DATE()))));

SET @n=1;
INSERT INTO TEMPORDER
SELECT @n:=@n+1 AS ROWNUM, CREATED_DATE FROM TORDER T
WHERE CREATED_DATE>=DATE(CONCAT(YEAR(CURRENT_DATE()), "-", MONTH(CURRENT_DATE()), "-", DAY(CURRENT_DATE())));

SELECT A.CREATED_DATE AS DATE1, B.CREATED_DATE AS DATE2, HOUR(TIMEDIFF(B.CREATED_DATE, A.CREATED_DATE))
FROM TEMPORDER A, TEMPORDER B
WHERE A.ROWNUM = B.ROWNUM-1
AND HOUR(TIMEDIFF(B.CREATED_DATE, A.CREATED_DATE))>2;

DROP TABLE IF EXISTS TEMPORDER;


DATE(CONCAT(YEAR(CURRENT_DATE()), "-", MONTH(CURRENT_DATE()), "-", DAY(CURRENT_DATE()))) is to get the start time of today. Let's say today is Feb 9, 2010, this will return 2010-02-09 00:00:00.



The first insert statement add the initial time of today.



+--------+---------------------+
| ROWNUM | CREATED_DATE |
+--------+---------------------+
| 1 | 2010-02-09 00:00:00 |
+--------+---------------------+


The SET and INSERT after that will pick up all the orders of today and populate them in the temp table



+--------+---------------------+
| ROWNUM | CREATED_DATE |
+--------+---------------------+
| 1 | 2010-02-09 00:00:00 |
| 2 | 2010-02-09 08:53:50 |
| 3 | 2010-02-09 11:54:04 |
| 4 | 2010-02-09 12:54:15 |
+--------+---------------------+


The Self associated query will generate the result below



+---------------------+---------------------+-----------+
| DATE1 | DATE2 | HOUR_DIFF |
+---------------------+---------------------+-----------+
| 2010-02-09 00:00:00 | 2010-02-09 08:53:50 | 8 |
| 2010-02-09 08:53:50 | 2010-02-09 11:54:04 | 3 |
+---------------------+---------------------+-----------+


The first record tells us there is no order in the first period (2010-02-09 00:00:00 | 2010-02-09 08:53:50), the same to the second record.

No comments:

Post a Comment