gpt4 book ai didi

MySQL - 根据最新日期和每列的 id 列表将行转换为列

转载 作者:行者123 更新时间:2023-11-30 21:53:14 25 4
gpt4 key购买 nike

即使经过数小时的搜索和尝试,我仍然无法弄清楚这一点。也许我没有选择正确的词?

好的,所以我有这样的事件表:

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_sectiondate) .嗯,基本上是这样的:

sectionA = id_section IN (1,2,3,4,5) 和 MAX(date)

sectionB = id_section IN (6,7,8,9,10) 和 MAX(date)

sectionC = id_section IN (11,12,13,14,15) 和 MAX(date)

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,但我仍然无法弄明白。

感谢您的帮助!

最佳答案

根据您当前的查询,如果每个 id_article 上有多个部分,我对子查询做了一些更改以确定最大值。此外,0 应该包含在 SectionA 的列表中

SELECT e1.id_article, 
MAX(CASE WHEN section = 'SectionA'
THEN CONCAT(e2.id_section, ' (', e2.date, ')') END) AS sectionA,
MAX(CASE WHEN section = 'SectionB'
THEN CONCAT(e2.id_section, ' (', e2.date, ')') END) AS sectionB,
MAX(CASE WHEN section = 'SectionC'
THEN CONCAT(e2.id_section, ' (', e2.date, ')') END) AS sectionC
FROM event e1
INNER JOIN (SELECT a.id_article,
a.id_section,
a.`date`,
a.section,
COUNT(*) row_number
FROM (SELECT *,
CASE WHEN id_section IN (0,1,2,3,4,5)
THEN 'SectionA'
WHEN id_section IN (6,7,8,9,10)
THEN 'SectionB'
WHEN id_section IN (11,12,13,14,15)
THEN 'SectionC'
END section
FROM `event`) a
INNER JOIN (SELECT *,
CASE WHEN id_section IN (0,1,2,3,4,5)
THEN 'SectionA'
WHEN id_section IN (6,7,8,9,10)
THEN 'SectionB'
WHEN id_section IN (11,12,13,14,15)
THEN 'SectionC'
END section
FROM `event`) b
ON a.id_article = b.id_article
AND a.section = b.section
AND a.`date` <= b.`date`
GROUP BY a.id_article,
a.id_section,
a.`date`
) e2
ON e1.id_article = e2.id_article
AND e1.date = e2.date
WHERE e2.row_number = 1
GROUP BY e1.id_article

结果

id_article  sectionA    sectionB    sectionC
1 3 (2012) (null) (null)
2 (null) 6 (2014) (null)
3 0 (2017) (null) 13 (2016)

关于MySQL - 根据最新日期和每列的 id 列表将行转换为列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46258858/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com