赞
踩
本文参考:http://blog.chinaunix.net/uid-411974-id-3990697.html,示例具业务场景略作改动。
- -- 气温采集表,每天每个整点的气温度数
- CREATE TABLE temp (
- id INT,
- time1 INT,
- time2 INT,
- time3 INT,
- time4 INT,
- receive_date DATE
- ) ;
-
- -- 初始化数据
- INSERT INTO `temp` (`id`, `time1`, `time2`, `time3`, `time4`, `receive_date`) VALUES('1','10','15','25','16','2016-05-11');
- INSERT INTO `temp` (`id`, `time1`, `time2`, `time3`, `time4`, `receive_date`) VALUES('2','9','14','26','15','2016-05-10');
- INSERT INTO `temp` (`id`, `time1`, `time2`, `time3`, `time4`, `receive_date`) VALUES('3','8','13','27','14','2016-05-09');
- INSERT INTO `temp` (`id`, `time1`, `time2`, `time3`, `time4`, `receive_date`) VALUES('4','7','12','28','13','2016-05-08');
- INSERT INTO `temp` (`id`, `time1`, `time2`, `time3`, `time4`, `receive_date`) VALUES('5','6','11','29','12','2016-05-07');
解决:使用cross join,具体用法可参考文章顶部的博客原文。
脚本如下:
- SELECT
- receive_date,
- SUBSTRING_INDEX(
- SUBSTRING_INDEX(sub_id, ',', seq),
- ',',
- - 1
- ) sub_id,
- seq
- FROM
- (SELECT
- 0 seq
- UNION
- SELECT
- 1 seq
- UNION
- SELECT
- 2 seq
- UNION
- SELECT
- 3 seq
- UNION
- SELECT
- 4 seq) sequence
- CROSS JOIN
- (SELECT
- CONCAT(
- p.time1,
- ',',
- p.time2,
- ',',
- p.time3,
- ',',
- p.time4
- ) sub_id,
- p.receive_date
- FROM
- temp p) temp2
- WHERE seq BETWEEN 1
- AND 4
- ORDER BY receive_date,
- seq ASC ;
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。