使用临时表很容易。首先通过以下方式总结您的数据:
CREATE TABLE sales_summary
(
id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
product_id CHAR(3) NOT NULL,
date DATETIME NOT NULL,
sold INT NOT NULL
)
SELECT
NULL AS id,
product_id,
DATE_FORMAT(date, '%Y-%m-%d %H:00:00') date,
SUM(sold) AS sold
FROM
sales
GROUP BY
product_id,
DATE_FORMAT(date, '%Y-%m-%d %H:00:00')
ORDER BY
1,2;
从该汇总表中,您可以创建报告:
SELECT
b.product_id,
a.date AS prev_hour,
b.date AS this_hour,
b.sold - a.sold AS diff_sold,
a.sold AS prev_sold,
b.sold AS this_sold
FROM
sales_summary a
INNER JOIN
sales_summary b ON b.id = a.id + 1 AND b.product_id = a.product_id
ORDER BY
a.product_id,
a.date DESC;
返回:
+------------+---------------------+---------------------+-----------+-----------+-----------+
| product_id | prev_hour | this_hour | diff_sold | prev_sold | this_sold |
+------------+---------------------+---------------------+-----------+-----------+-----------+
| ABC | 2013-04-20 10:00:00 | 2013-04-20 11:00:00 | 40 | 10 | 50 |
| ABC | 2013-04-20 09:00:00 | 2013-04-20 10:00:00 | -10 | 20 | 10 |
| DEF | 2013-04-20 09:00:00 | 2013-04-20 10:00:00 | -10 | 30 | 20 |
| HIJ | 2013-04-20 09:00:00 | 2013-04-20 10:00:00 | 10 | 30 | 40 |
+------------+---------------------+---------------------+-----------+-----------+-----------+
一个工作示例位于http://sqlfiddle.com/#!2/897d9/1/0