当前位置:   article > 正文

Mysql group_concat的反向应用实现(Mysql列转行)

mysql group_concat的反向

本文参考:http://blog.chinaunix.net/uid-411974-id-3990697.html,示例具业务场景略作改动。


  1. -- 气温采集表,每天每个整点的气温度数
  2. CREATE TABLE temp (
  3. id INT,
  4. time1 INT,
  5. time2 INT,
  6. time3 INT,
  7. time4 INT,
  8. receive_date DATE
  9. ) ;
  10. -- 初始化数据
  11. INSERT INTO `temp` (`id`, `time1`, `time2`, `time3`, `time4`, `receive_date`) VALUES('1','10','15','25','16','2016-05-11');
  12. INSERT INTO `temp` (`id`, `time1`, `time2`, `time3`, `time4`, `receive_date`) VALUES('2','9','14','26','15','2016-05-10');
  13. INSERT INTO `temp` (`id`, `time1`, `time2`, `time3`, `time4`, `receive_date`) VALUES('3','8','13','27','14','2016-05-09');
  14. INSERT INTO `temp` (`id`, `time1`, `time2`, `time3`, `time4`, `receive_date`) VALUES('4','7','12','28','13','2016-05-08');
  15. INSERT INTO `temp` (`id`, `time1`, `time2`, `time3`, `time4`, `receive_date`) VALUES('5','6','11','29','12','2016-05-07');



问题:查询5月份温度高于15度的次数,sql如何写?
如果列表较多,如100列,sql如何写?

解决:使用cross join,具体用法可参考文章顶部的博客原文。

脚本如下:

  1. SELECT
  2. receive_date,
  3. SUBSTRING_INDEX(
  4. SUBSTRING_INDEX(sub_id, ',', seq),
  5. ',',
  6. - 1
  7. ) sub_id,
  8. seq
  9. FROM
  10. (SELECT
  11. 0 seq
  12. UNION
  13. SELECT
  14. 1 seq
  15. UNION
  16. SELECT
  17. 2 seq
  18. UNION
  19. SELECT
  20. 3 seq
  21. UNION
  22. SELECT
  23. 4 seq) sequence
  24. CROSS JOIN
  25. (SELECT
  26. CONCAT(
  27. p.time1,
  28. ',',
  29. p.time2,
  30. ',',
  31. p.time3,
  32. ',',
  33. p.time4
  34. ) sub_id,
  35. p.receive_date
  36. FROM
  37. temp p) temp2
  38. WHERE seq BETWEEN 1
  39. AND 4
  40. ORDER BY receive_date,
  41. seq ASC ;



声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/75032
推荐阅读
相关标签
  

闽ICP备14008679号