【发布时间】:2021-12-22 22:45:50
【问题描述】:
我想在查询中按三列进行分区:
- 用户名
- 取消月份年份。
- 保留月份年份。
我使用的行号和分区如下
row_number() over (partition by user_id ,cast ( date_format(cancelation_date,'yyyyMM') as integer),cast ( date_format(retention_date,'yyyyMM') as integer) order by cast ( date_format(cancelation_date,'yyyyMM') as integer) asc, cast ( date_format(retention_date,'yyyyMM') as integer) asc) as row_count
我得到的输出示例:
| user_id |cancelation_date |cancelation_month_year|retention_date|retention_month_year|row_count|
| -------- | -------------- |----------------------|--------------|--------------------|---------|
| 566 | 28-5-2020 | 202005 | 20-7-2020 | 202007 |1 |
| 566 | 28-5-2020 | 202005 | 30-7-2-2020 | 202007 |2 |
我想得到的输出示例:
| user_id | cancelation_date | cancelation_month_year | retention_date | retention_month_year | row_count |
|---|---|---|---|---|---|
| 566 | 28-5-2020 | 202005 | 20-7-2020 | 202007 | 1 |
| 566 | 28-5-2020 | 202005 | 30-7-2-2020 | 202007 | 1 |
请注意,用户可能有多个取消月份,例如,如果他在八月取消,我希望八月份的所有日期的行数 =2,依此类推。
为什么 partition by 是按保留日期分区而不是按保留月份年份分区,这一点并不明显。
【问题讨论】:
-
我觉得
row_number不是您想要的,而是您对dense_rank感兴趣,您会在其中获得预期的输出。 -
没错。 dense_rank 为我工作
-
如果您有时间,如果您的回答对您有用,我相信他们会很感激您将其标记为正确的。
标签: apache-spark pyspark apache-spark-sql partition-by