mysql中连续出现_MySQL分组连续出现

这篇博客探讨了一个SQL查询,用于在给定的表格中找到连续的团队年份序列。查询通过连接子查询找出每个团队的开始年份、结束年份和连续年份总数,并用示例数据进行了说明。解决方案利用了LEFT JOIN和条件过滤来识别连续的记录。此外,提到了CommonQueriesTree工具可能对此类问题有所帮助。
摘要由CSDN通过智能技术生成

只要您的表格如下所示:

"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,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,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,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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值