I have a log table in which I keep user login records.
CREATE TABLE public.login
(
id bigint NOT NULL,
copy_id bigint,
create_date timestamp without time zone,
version integer NOT NULL DEFAULT 0,
firm_id bigint,
language_id bigint,
user_id bigint,
channel character varying(255),
error character varying(255),
ip character varying(255),
username character varying(255),
otp character varying(255),
account_period_id bigint,
login_code character varying(255),
CONSTRAINT login_pkey PRIMARY KEY (id),
CONSTRAINT fkilkkn9n0fkwoenwtpljjyhd89 FOREIGN KEY (user_id)
REFERENCES public."user" (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION,
CONSTRAINT fkj2ff261eu4uy2dc7ehpto877k FOREIGN KEY (language_id)
REFERENCES public.language (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION,
CONSTRAINT fkoi2rpag6j9pl6y21l74sxfic0 FOREIGN KEY (account_period_id)
REFERENCES public.account_period (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION,
CONSTRAINT fkpsi5sd9hd43btcd20brrbltf8 FOREIGN KEY (firm_id)
REFERENCES public.firm (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
)
For example, finding the number of logins of users but dividing them into weeks
1.2.3.4.5.6.7. I want to set it to week
-
a user logged in 5 times in the 1st week
-
a user 2 . logged in 3 times a week,
-
a user logged in 5 times in the 3rd week
-
a user 4 . logged in 3 times a week,
-
a user logged in 5 times in the 5th week
-
a user 6 . logged in 3 times a week,
-
a user logged in 5 times in the 7th week
-
b user logged in 51 times in the 1st week
-
b user 2 . logged in 53 times in a week,
-
b user logged in 54 times in the 3rd week
-
b user 4 . logged in 39 times in a week,
-
b user logged in 5 times in the 5th week
-
b user 6 . logged in 13 times in a week,
-
b user logged in 15 times in the 7th week
I tried the following:
SELECT
user_id,
DATE_TRUNC('week', create_date) AS week_start_date,
COUNT(*) AS login_count
FROM
login
GROUP BY
user_id,
DATE_TRUNC('week', create_date)
ORDER BY
user_id,
week_start_date;
output:
enter image description here
But that’s not what I want
What I want is to write zero even if the user with user_id is not logged in, but I could not achieve this.
enter image description here