在 dense_rank window 函数中添加计数条件 SQL
Add a counting condition into dense_rank window Function SQL
我有一个功能可以计算您访问了多少次以及您是否已转换。
我想要的是 dense_rank 重新开始计数,如果有转换:
SELECT
uid,
channel,
time,
conversion,
dense_rank() OVER (PARTITION BY uid ORDER BY time asc) as visit_order
FROM table
当前table输出:
此客户 (uid
) 在访问 18 时进行了一次转化,现在我希望 dense_rank
的 visit_order
计数从同一客户的 0 重新开始,直到它达到下一次非转化-无效的。
看到这个(我不喜欢“试试这个”):
SELECT
id,
ts,
conversion,
-- SC,
ROW_NUMBER() OVER (PARTITION BY id,SC) R
FROM (
SELECT
id,
ts,
conversion,
-- COUNT(conversion) OVER (PARTITION BY id, conversion=0 ORDER BY ts ) CC,
SUM(CASE WHEN conversion=1 THEN 1000 ELSE 1 END) OVER (PARTITION BY id ORDER BY ts ) - SUM(CASE WHEN conversion=1 THEN 1000 ELSE 1 END) OVER (PARTITION BY id ORDER BY ts )%1000 SC
FROM sample
ORDER BY ts
) x
ORDER BY ts;
输出:
id
ts
conversion
R
1
2022-01-15 10:00:00
0
1
1
2022-01-16 10:00:00
0
2
1
2022-01-17 10:00:00
0
3
1
2022-01-18 10:00:00
1
1
1
2022-01-19 10:00:00
0
2
1
2022-01-20 10:00:00
0
3
1
2022-01-21 10:00:00
0
4
1
2022-01-22 10:00:00
0
5
1
2022-01-23 10:00:00
0
6
1
2022-01-24 10:00:00
0
7
1
2022-01-25 10:00:00
1
1
1
2022-01-26 10:00:00
0
2
1
2022-01-27 10:00:00
0
3
我有一个功能可以计算您访问了多少次以及您是否已转换。 我想要的是 dense_rank 重新开始计数,如果有转换:
SELECT
uid,
channel,
time,
conversion,
dense_rank() OVER (PARTITION BY uid ORDER BY time asc) as visit_order
FROM table
当前table输出:
此客户 (uid
) 在访问 18 时进行了一次转化,现在我希望 dense_rank
的 visit_order
计数从同一客户的 0 重新开始,直到它达到下一次非转化-无效的。
看到这个(我不喜欢“试试这个”):
SELECT
id,
ts,
conversion,
-- SC,
ROW_NUMBER() OVER (PARTITION BY id,SC) R
FROM (
SELECT
id,
ts,
conversion,
-- COUNT(conversion) OVER (PARTITION BY id, conversion=0 ORDER BY ts ) CC,
SUM(CASE WHEN conversion=1 THEN 1000 ELSE 1 END) OVER (PARTITION BY id ORDER BY ts ) - SUM(CASE WHEN conversion=1 THEN 1000 ELSE 1 END) OVER (PARTITION BY id ORDER BY ts )%1000 SC
FROM sample
ORDER BY ts
) x
ORDER BY ts;
输出:
id | ts | conversion | R |
---|---|---|---|
1 | 2022-01-15 10:00:00 | 0 | 1 |
1 | 2022-01-16 10:00:00 | 0 | 2 |
1 | 2022-01-17 10:00:00 | 0 | 3 |
1 | 2022-01-18 10:00:00 | 1 | 1 |
1 | 2022-01-19 10:00:00 | 0 | 2 |
1 | 2022-01-20 10:00:00 | 0 | 3 |
1 | 2022-01-21 10:00:00 | 0 | 4 |
1 | 2022-01-22 10:00:00 | 0 | 5 |
1 | 2022-01-23 10:00:00 | 0 | 6 |
1 | 2022-01-24 10:00:00 | 0 | 7 |
1 | 2022-01-25 10:00:00 | 1 | 1 |
1 | 2022-01-26 10:00:00 | 0 | 2 |
1 | 2022-01-27 10:00:00 | 0 | 3 |