mysql 多列合并一列,一行转多行

小灰灰 2022-11-26 11:55 415阅读 0赞

思路:将两列日期先格式化成以yyyy-MM-dd格式,再将两列合并成一列,并且以逗号分隔开,再根据逗号将一列中的一行分割成多行,再分组去重

  1. CREATE TABLE `t_product` (
  2. `id` varchar(225) NOT NULL,
  3. `start_time` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  4. `end_time` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  5. PRIMARY KEY (`id`)
  6. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
  7. -- ----------------------------
  8. -- Records of t_product
  9. -- ----------------------------
  10. INSERT INTO `t_product` VALUES ('1', '2020-08-11 19:20:31', '2020-08-11 22:20:36');
  11. INSERT INTO `t_product` VALUES ('2', '2020-08-12 19:09:09', '2020-08-12 22:20:36');
  12. INSERT INTO `t_product` VALUES ('3', '2020-08-13 19:09:14', '2020-08-13 22:20:36');
  13. INSERT INTO `t_product` VALUES ('4', '2020-08-11 19:06:59', '2020-08-14 22:20:36');
  14. SELECT * FROM (
  15. SELECT substring_index(
  16. substring_index(
  17. all_date,
  18. ',',
  19. b.help_topic_id + 1
  20. ),
  21. ',' ,- 1
  22. ) AS all_date_group FROM (
  23. select concat(DATE_FORMAT(p.start_time,'%Y-%m-%d'), ',', DATE_FORMAT(p.end_time,'%Y-%m-%d')) as all_date FROM t_product p
  24. ) pp JOIN mysql.help_topic b ON b.help_topic_id < (
  25. length(all_date) - length(
  26. REPLACE (all_date, ',', '')
  27. ) + 1
  28. )
  29. ) ss GROUP BY ss.all_date_group

发表评论

表情:
评论列表 (有 0 条评论,415人围观)

还没有评论,来说两句吧...

相关阅读