获取连续一周的条目

2cmtqfgy  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(273)

我有一个mysql表,有两个id列和一个date列。我正在尝试根据日期列获取连续的周数

|ID|ID2|Date      |
|1 | 1 |2018-01-01|
|1 | 1 |2018-01-08|
|1 | 1 |2018-01-15|
|2 | 1 |2018-01-01|
|2 | 1 |2018-01-08|
|2 | 2 |2018-01-01|

我想要的是这样一张table

|ID |ID2|Consecutive Week|
|1  | 1 |3               |
|2  | 1 |2               |
|2  | 2 |1               |

我被以下代码困住了:

SELECT a.ID, a.ID2 ,consec_set, COUNT(1) AS consec_count
FROM
(
   SELECT IF(b.Date IS NULL, @val:=@val+1, @val) AS consec_set,a.ID2
   FROM tbl a
   CROSS JOIN (SELECT @val:=0) var_init
   LEFT JOIN tbl b ON 
       a.ID = b.ID AND
       a.ID2 = b.ID2 AND
       YEARWEEK(a.Date ,1) = YEARWEEK(b.Date ,1) + 1
   WHERE a.ID= 1
) a
GROUP BY a.consec_set;

我达到这个代码遵循几个指南在这里,但他们只有连续几天,只有一个id。提前谢谢。

bvjveswy

bvjveswy1#

不知怎的,我成功了sql。不过有点复杂。

SELECT id, id2, Max(cnt) FROM (
    SELECT id, id2, Count(id) AS CNT FROM (
        SELECT *, (
            SELECT @num:=Ifnull(@num,0)) AS grouper, 
                   @num := IF(cntn=0, @num+1, @num) AS row_number  
            FROM (
                SELECT a.id, a.id2, a.wno, b.id IS NOT NULL AS CNTN 
                FROM (
                    SELECT DISTINCT id, id2, Week(pdate) AS WNO FROM listing) a
                    LEFT JOIN
                        (SELECT DISTINCT id, id2, Week(pdate) AS WNO FROM listing) b
                    ON a.wno = b.wno - 1 AND a.id = b.id AND a.id2 = b.id2
                    ORDER BY a.id, a.id2, a.wno
                ) d 
            ) e GROUP BY e.id, e.id2, e.grouper
        ) f GROUP BY f.id, f.id2

以下是我在评论中提到的所有案例的要点:
http://sqlfiddle.com/#!9/b785df/71型
从里到外解释:
从表中选择了不同的weeknumber、id、id2值
加入了1。如果表存在,则在连续的表上再次将其自身
无论连续记录是否存在,都将连接的行转换为布尔值。
用1、2、3等索引将连续的行分组
已选择组的计数
选择具有相同id和id1的最大组数。

juud5qan

juud5qan2#

没有答案。评论时间太长。
考虑以下几点:

SELECT *, YEARWEEK(date,1) yw FROM my_table;
+-----+-----+------------+--------+
| ID1 | ID2 | Date       | yw     |
+-----+-----+------------+--------+
|   1 |   1 | 2018-01-01 | 201801 |
|   1 |   1 | 2018-01-08 | 201802 |
|   1 |   1 | 2018-01-15 | 201803 |
|   2 |   1 | 2018-01-01 | 201801 |
|   2 |   1 | 2018-01-07 | 201801 |
|   2 |   2 | 2018-01-01 | 201801 |
+-----+-----+------------+--------+

1,1 = 3 consecutive weeks
2,1 = 1 week
2,2 = 1 week

相关问题