题解 | #某宝店铺连续2天及以上购物的用户及其对应的天数#
某宝店铺连续2天及以上购物的用户及其对应的天数
http://www.nowcoder.com/practice/63ac3be0e4b44cce8dd2619d2236c3bf
先用需要判断是否连续的col(这里是DAY(sales_date))减去对于每个人的排序,如果连续那么差值应该恒定不变。再将其作为窗口函数中的条件进行筛选,用子查询找出计数大于等于2的行即可。
SELECT *
FROM
(
SELECT DISTINCT user_id, COUNT(*) OVER(PARTITION BY user_id, const_col) AS days_count
FROM
(
SELECT user_id, sales_date, DAY(sales_date) + 20 - ROW_NUMBER() OVER(PARTITION BY user_id ORDER BY sales_date) AS const_col
FROM sales_tb
) AS t1
) AS t2
WHERE days_count >= 2