简体   繁体   中英

MySQL (Group Min Query)

I have this table my_table with 3 columns as follows

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);

Is it possible to flatten/group this by a query such that the output will be

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

This is puzzling me for almost 3 days now; Creating a temp table and adding trick column id for grouping didn't do me any good

I hope you can help me.

Thanks

Try this

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

This may be very inefficient though, depending on your case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM