我正在尝试根据月份验证登录的用户。 SQL
当前df
user id date
P1302 2023-11-01
P1302 2023-10-01
P1302 2023-09-01
P1302 2023-08-01
P1302 2023-07-01
P1302 2023-06-01
P1301 2023-11-01
P1301 2023-10-01
P1301 2023-08-01
P1301 2023-07-01
P1301 2023-06-01
预期结果
user id Jun Jul aug sep oct nov
1302 1 1 1 1 1 1
1301 1 1 1 0 1 1
您可以通过条件聚合来做到这一点:
select
user_id,
-- extract(year from date) as year,
max(extract(month from date) = 1) as jan,
max(extract(month from date) = 12) as dec
from t
group by user_id --, extract(year from date)
解决问题的一种常见方法是对 case 表达式使用 count:
select count(case month(dt) = 1 then 1 end) as jan
, count(case month(dt) = 2 then 1 end) as feb
, ...
from ...