【发布时间】:2018-02-25 18:49:44
【问题描述】:
即使经过数小时的搜索和尝试,我仍然无法弄清楚这一点。也许我没有选择正确的词?
好的,所以我有这样的事件表:
EVENT
+----+------------+------------+------+
| id | id_article | id_section | date |
+----+------------+------------+------+
| 1 | 1 | 1 | 2011 |
| 2 | 1 | 3 | 2012 |
| 3 | 2 | 7 | 2013 |
| 4 | 2 | 6 | 2014 |
| 5 | 3 | 14 | 2015 |
| 6 | 3 | 13 | 2016 |
| 7 | 3 | 0 | 2017 |
+----+------------+------------+------+
我想将此表转换为三个不同的列,其中每列包含 id_section 列表中的最新事件(id_section 和 date) .嗯,基本上是这样的:
sectionA = id_section IN (1,2,3,4,5) 和 MAX(日期)
sectionB = id_section IN (6,7,8,9,10) 和 MAX(date)
sectionCtrong> = id_section IN (11,12,13,14,15) 和 MAX(日期)
DESIRED RESULT
+------------+----------+----------+-----------+
| id_article | sectionA | sectionB | sectionC | #id_event
+------------+----------+----------+-----------+
| 1 | 3 (2012) | null | null | #id 2
| 2 | null | 6 (2014) | null | #id 4
| 3 | 0 (2017) | null | 13 (2016) | #id 7, 6 <-- two latest events
+------------+----------+----------+-----------+
这是我现在拥有的SqlFiddle - 它只选择每个 id_article 的最新事件:
INSUFFICIENT RESULT
+------------+----------+----------+-----------+
| id_article | sectionA | sectionB | sectionC | #id_event
+------------+----------+----------+-----------+
| 1 | 3 (2012) | null | null | #id 2
| 2 | null | 6 (2014) | null | #id 4
| 3 | 0 (2017) | null | null | #id 7 <-- only latest event
+------------+----------+----------+-----------+
我尝试使用更多的 JOINS,但我仍然无法弄清楚。
感谢您的帮助!
【问题讨论】:
-
如果有关系?
-
@GordonLinoff 然后可能选择具有更高 id(事件)的那个
标签: mysql sql pivot-table greatest-n-per-group groupwise-maximum