将多个具有相同ID的行合并在一起

时间:2020-09-07 13:45:40

标签: mysql sql join pivot

我在使用SQL查询时遇到麻烦。我有两个桌子。

我的第一张桌子:

+------------+-------------+---------------+
| id_mission | Some column | Other column  |
+------------+-------------+---------------+
|      1     |     ...     |      ...      |
|      2     |     ...     |      ...      |
+------------+-------------+---------------+

我的第二张桌子:

+------------+-------------+---------+
| id_mission | id_category | points  |
+------------+-------------+---------+
|          1 |           1 |       3 |
|          1 |           2 |       4 |
|          1 |           3 |       4 |
|          1 |           4 |       8 |
|          2 |           1 |      -4 |
|          2 |           2 |       3 |
|          2 |           3 |       1 |
|          2 |           4 |      -7 |
+------------+-------------+---------+

我想在SELECT请求中得到这种结果

+------------+-------------+--------------+---------------+----------------+
| id_mission | Some column | Other column | id_category 1 | id_category X  |
+------------+-------------+--------------+---------------+----------------+
|          1 |         ... |          ... |           ... |            ... |
|          2 |         ... |          ... |           ... |            ... |
+------------+-------------+--------------+---------------+----------------+

我已经在前两列中尝试过此方法,但是它不起作用,我也尝试过GROUP_CONCAT,它有效,但这不是我想要的结果。

SELECT m.id_mission ,mc.id_category 1,mc1.id_category 2
from mission m 
left join mission_category mc on m.id_mission = mc.id_mission 
left join mission_category mc1 on m.id_mission = mc1.id_mission

有人可以帮我吗?

1 个答案:

答案 0 :(得分:2)

您可以使用条件聚合。假设您想按类别旋转fun findDate(dayOfMonth: Int): LocalDate { val now = LocalDate.now() val currentDayOfMonth = now.getDayOfMonth() if (currentDayOfMonth <= dayOfMonth) { // use the current month with the given day of month return now.withDayOfMonth(dayOfMonth) // subtract a day (will change the month when dayOfMonth == 1) .minusDays(1) // and add a month .plusMonths(1) } else { // otherwise just take the current month with the given day of month return now.withDayOfMonth(dayOfMonth) // and subtract a day .minusDays(1) } } 值:

points

这假定select t1.*, max(case when t2.id_category = 1 then points end) category_1, max(case when t2.id_category = 2 then points end) category_2, max(case when t2.id_category = 3 then points end) category_3 from t1 inner join t2 on t2.id_mission = t1.id_mission group by t1.id_mission id_mission的主键(否则,您需要枚举t1select子句中想要的列)。 / p>