SQL postgres提取周

时间:2018-04-19 07:50:47

标签: sql postgresql extract

您能否帮我修改以下代码,以便每周提取不同的user_id,而不是每个月? user_id在给定的一周内只能出现一次。

 SELECT
COUNT(DISTINCT user_id),
 EXTRACT(YEAR FROM created_at) Y,
EXTRACT(MONTH FROM created_at) M
FROM user_logins
WHERE created_at >= '2017-01-01'
 AND created_at <= '2018-04-10' 
GROUP BY EXTRACT(YEAR FROM created_at),EXTRACT(MONTH FROM created_at)
ORDER BY Y,M

OR

SELECT
  COUNT(DISTINCT user_id),
  to_char(created_at, 'YYYY-MM') YM
FROM user_logins
WHERE created_at >= '2017-01-01'
  AND created_at <= '2018-04-10' 
GROUP BY to_char(created_at, 'YYYY-MM')
ORDER BY YM

2 个答案:

答案 0 :(得分:0)

摘要会为您提供一年中的周数,因此,如果您有几年,则计数将为所有年份 - 因此它不是每周,而是&#34;对于任何一年的周数和#34;:

t=# with c(d) as (values('2016-04-19'::date),('2017-04-19'))
select count(*), extract(week from d) from c group by extract(week from d);
 count | date_part
-------+-----------
     2 |        16
(1 row)

如果您希望每周数据,根据唯一时间标识符,请改为使用date_trunc

t=# with c(d) as (values('2016-04-19'::date),('2017-04-19'))
select count(*), date_trunc('week', d) from c group by date_trunc('week', d);
 count |       date_trunc
-------+------------------------
     1 | 2017-04-17 00:00:00+00
     1 | 2016-04-18 00:00:00+00
(2 rows)

答案 1 :(得分:0)

您可以使用WW使用IW来提取周数或标准ISO week。你必须把年份包括在内,因为“当前”年有几个星期,部分在去年或明年。使用IW时,您还需要使用与该周数对应的“ISO年份”

SELECT COUNT(DISTINCT user_id),
       to_char(created_at, 'IYYYY-IW') as week
FROM user_logins
WHERE created_at >= '2017-01-01'
  AND created_at <= '2018-04-10' 
GROUP BY to_char(created_at, 'IYYYY-IW')
ORDER BY week;

这也可以使用extract()函数完成:

SELECT COUNT(DISTINCT user_id),
       extract(isoyear from created_at) as year, 
       extract(week from created_at) as week
FROM user_logins
WHERE created_at >= '2017-01-01'
  AND created_at <= '2018-04-10' 
GROUP BY extract(isoyear from created_at), extract(week from created_at) 
ORDER BY week;