MySQL(组最小查询)

时间:2014-03-20 08:04:15

标签: mysql

我有这个表my_table,其中包含3列,如下所示

DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table
(id INT NOT NULL
,date DATE NOT NULL
,val INT NOT NULL
,PRIMARY KEY(id,date)
);

INSERT INTO my_table VALUES
(38,'2014-02-16', 3),
(38,'2014-02-17', 3),
(38,'2014-02-18', 2),
(38,'2014-02-19', 1),
(38,'2014-02-20', 3),
(38,'2014-02-21', 3),
(38,'2014-02-22', 3),
(38,'2014-02-24', 3),
(38,'2014-02-25', 3),
(38,'2014-02-26', 3),
(38,'2014-02-27', 3),
(38,'2014-02-28', 3),
(38,'2014-03-01', 3),
(38,'2014-03-02', 2),
(38,'2014-03-03', 2);

是否可以通过查询对其进行展平/分组,以使输出为

38, '2014-02-16', 3
38, '2014-02-18', 2
38, '2014-02-19', 1
38, '2014-02-20', 3
38, '2014-03-02', 2

这让我困惑了将近3天;创建临时表并添加技巧列ID进行分组并没有给我带来任何好处

我希望你能帮助我。

由于

1 个答案:

答案 0 :(得分:0)

试试这个

SELECT t1.employee_id, t1.date, t1.section_id FROM
tableA t1
LEFT JOIN tableA t2
ON t1.date = ADDDATE( t2.date, INTERVAL 1 DAY)
WHERE ISNULL(t2.section_id) OR t1.section_id <> t2.section_id
ORDER BY t1.date

这可能效率非常低,具体取决于您的情况。