gpt4 book ai didi

MySQL分组连续出现

转载 作者:可可西里 更新时间:2023-11-01 08:22:28 26 4
gpt4 key购买 nike

我想按连续出现的列值对查询结果进行分组。假设我有一张表格,其中列出了每年比赛的获胜者,如下所示:

year    team_name
2000 AAA
2001 CCC
2002 CCC
2003 BBB
2004 AAA
2005 AAA
2006 AAA

我想要一个输出的查询:

start_end    total   team_name
2000 1 AAA
2001-2002 2 CCC
2003 1 BBB
2004-2006 3 AAA

我不太担心“start_end”的格式,只要我有开始和结束或范围(例如,可以使用 GROUP_CONCAT 生成 2004,2005,2006 而不是 2004-2006,那会还是可以的)。

最佳答案

前提是你的表格是这样的:

"id";"year";"team"
"1";"2000";"AAA"
"2";"2001";"CCC"
"3";"2002";"CCC"
"4";"2003";"BBB"
"5";"2004";"AAA"
"6";"2005";"AAA"
"7";"2006";"AAA"

这个查询应该可以解决问题:

SELECT a.year AS start
, MIN(c.year) AS end
, MIN(c.year)-a.year+1 AS total
, CONCAT_WS('-', a.year, IF(a.year = min(c.year), NULL, min(c.year))) as start_end
, a.team
FROM
( SELECT x.year, x.team, COUNT(*) id
FROM results x
JOIN results y
ON y.year <= x.year
GROUP BY x.id
) AS a
LEFT JOIN
( SELECT x.year, x.team, COUNT(*) id
FROM results x
JOIN results y
ON y.year <= x.year
GROUP BY x.id
) AS b ON a.id = b.id + 1 AND b.team = a.team
LEFT JOIN
( SELECT x.year, x.team, COUNT(*) id
FROM results x
JOIN results y
ON y.year <= x.year
GROUP BY x.id
) AS c ON a.id <= c.id AND c.team = a.team
LEFT JOIN
( SELECT x.year, x.team, COUNT(*) id
FROM results x
JOIN results y
ON y.year <= x.year
GROUP BY x.id
) AS d ON c.id = d.id - 1 AND d.team = c.team
WHERE b.id IS NULL AND c.id IS NOT NULL AND d.id IS NULL
GROUP BY start;

顺便说一句,您可能会找到 Common Queries Tree方便解决这些问题(检查“查找序列中的上一个和下一个值”的答案):p。

关于MySQL分组连续出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3476761/

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