统计PostgreSQL中的第一条记录
Count the first record in PostgreSQL
我有一个 table 这样的(在我的用户过滤器之后)
ID user_id action_type created_date
1 123 3 27/1/2022
2 123 3 30/1/2022
3 123 3 08/03/2022
4 123 3 08/03/2022
然后我有这个查询
select date_trunc('week', created_date::timestamptz) as "Week"
,count(distinct user_id) filter (where action_type = 3) as "linkbank"
From action_logs
Where action_type = 3 and user_id = '123'
Group by "Week"
查询结果是这样的
Week linkbank
24/01/2022 1
07/03/2022 1
所以如果我必须第一次计算客户端链接库,我应该在查询中更改什么?
例如,如果我用 user_id =123
更改查询,我希望结果只取第一行
我会尝试你评论的一切。
感谢。
如果你只想要一个 user_id
select date_trunc('week', created_date::timestamptz) as "Week"
,count(distinct user_id) filter (where action_type = 3) as "linkbank"
From action_logs
Where action_type = 3 and user_id = 123
Group by "Week"
order by "Week"
limit 1;
如果您希望所有用户都能使用
with l as (
select row_number() over (partition by user_id order by user_id, date_trunc('week', created_date::timestamptz)) as rn,user_id, date_trunc('week', created_date::timestamptz) as "Week"
,count(distinct user_id) filter (where action_type = 3) as "linkbank"
From action_logs
Where action_type = 3
Group by user_id,"Week"
)
select * from l where rn = 1
我有一个 table 这样的(在我的用户过滤器之后)
ID user_id action_type created_date
1 123 3 27/1/2022
2 123 3 30/1/2022
3 123 3 08/03/2022
4 123 3 08/03/2022
然后我有这个查询
select date_trunc('week', created_date::timestamptz) as "Week"
,count(distinct user_id) filter (where action_type = 3) as "linkbank"
From action_logs
Where action_type = 3 and user_id = '123'
Group by "Week"
查询结果是这样的
Week linkbank
24/01/2022 1
07/03/2022 1
所以如果我必须第一次计算客户端链接库,我应该在查询中更改什么?
例如,如果我用 user_id =123
更改查询,我希望结果只取第一行
我会尝试你评论的一切。
感谢。
如果你只想要一个 user_id
select date_trunc('week', created_date::timestamptz) as "Week"
,count(distinct user_id) filter (where action_type = 3) as "linkbank"
From action_logs
Where action_type = 3 and user_id = 123
Group by "Week"
order by "Week"
limit 1;
如果您希望所有用户都能使用
with l as (
select row_number() over (partition by user_id order by user_id, date_trunc('week', created_date::timestamptz)) as rn,user_id, date_trunc('week', created_date::timestamptz) as "Week"
,count(distinct user_id) filter (where action_type = 3) as "linkbank"
From action_logs
Where action_type = 3
Group by user_id,"Week"
)
select * from l where rn = 1