如何显示行到列的日期顺序

问题描述 投票:-1回答:1

具有主要字段idPeriod和几百个记录的表周期。具有idPeriod和dateClass的表date_classes也有要显示的名称。每个名称都有相同的时期和5个日期。

每个时期有5个日期。

+-----------+------------+
| idPeriode | dateClass  |
+-----------+------------+
|    302367 | 2020-02-18 |
|    302367 | 2020-02-25 |
|    302367 | 2020-03-03 |
|    302367 | 2020-03-10 |
|    302367 | 2020-03-17 |
+-----------+------------+

我想展示:

+----------+---------------------+------------+------------+------------+------------+
| Name     | Period | Date1      | Date2      | Date3      | Date4      | Date5      |
+----------+---------------------+------------+------------+------------+------------+
| Bousquet | 302367 | 2020-02-18 | 2020-02-25 | 2020-03-03 | 2020-03-10 | 2020-03-17 |
| Grignon  | 302367 | 2020-02-18 | 2020-02-25 | 2020-03-03 | 2020-03-10 | 2020-03-17 |
| Rajotte  | 302367 | 2020-02-18 | 2020-02-25 | 2020-03-03 | 2020-03-10 | 2020-03-17 |
| Vandal   | 302367 | 2020-02-18 | 2020-02-25 | 2020-03-03 | 2020-03-10 | 2020-03-17 |
| Tessier  | 302367 | 2020-02-18 | 2020-02-25 | 2020-03-03 | 2020-03-10 | 2020-03-17 |
| Beauvais | 302367 | 2020-02-18 | 2020-02-25 | 2020-03-03 | 2020-03-10 | 2020-03-17 |
+----------+--------+------------+------------+------------+------------+------------+
mysql rows
1个回答
0
投票

尚不清楚为什么要这样做,但是可以通过在查询中实现一些功能来实现。请参考以下查询示例:

SELECT NAME, idperiode,
       SUBSTRING_INDEX(dateclass,',',1) AS date_1,
       SUBSTRING_INDEX(SUBSTRING_INDEX(dateclass,',',2),',',-1) AS date_2,
       SUBSTRING_INDEX(SUBSTRING_INDEX(dateclass,',',3),',',-1) AS date_3,
       SUBSTRING_INDEX(SUBSTRING_INDEX(dateclass,',',4),',',-1) AS date_4,
       SUBSTRING_INDEX(dateclass,',',-1) AS date_5
FROM       
(SELECT NAME,
       idperiode,
       GROUP_CONCAT(dateclass ORDER BY dateclass) AS dateclass 
 FROM mytable
 GROUP BY NAME, idperiode) A;

[第一部分是使用GROUP_CONCAT组合所有日期的子查询(假定所有这些仅在一个表中)。然后使用SUBSTRING_INDEX分隔成组日期。 You can view the demo fiddle here

如果有两个没有关系的表,则可以在表上使用CROSS JOIN。我在子查询中也做了prepared the fiddle here稍加修改,而外部查询的功能仍然相同。

© www.soinside.com 2019 - 2024. All rights reserved.