连续一周获得参赛作品

时间:2018-01-19 11:47:55

标签: mysql

我有一个带有两个ID列和一个日期列的MYSQL表。我想根据日期栏

获得连续几周的数量
|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|

我想要实现的是像这样的表

|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。提前谢谢。

2 个答案:

答案 0 :(得分:1)

不知怎的,我成功了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

从内到外解释:

  1. 从表
  2. 中选择不同的WeekNumber,ID,ID2值
  3. 在连续的表格上再次加入1.表格(如果存在)
  4. 无论连续记录是否存在,都将已连接的行转换为布尔值。
  5. 使用1,2,3等索引对连续行进行分组
  6. 选择了小组的数量
  7. 选择具有相同ID和ID1的最大组。

答案 1 :(得分:0)

不是答案。评论太长了。

请考虑以下事项:

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