V
V
vbNoName2019-04-11 20:03:28
PostgreSQL
vbNoName, 2019-04-11 20:03:28

How to select users whose first comment falls within a given range?

There is a table of users, and a table of comments.

CREATE TABLE users (
  id SERIAL NOT NULL PRIMARY KEY
);

CREATE TABLE comments (
  id SERIAL NOT NULL PRIMARY KEY,
  user_id INT NOT NULL,
  created_at TIMESTAMP NOT NULL DEFAULT NOW(),
  CONSTRAINT fk_users_comment FOREIGN KEY (user_id) REFERENCES users (id)
  ON UPDATE CASCADE
  ON DELETE CASCADE 
)

How to select users whose first comment's created_at falls within a given range?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
d-stream, 2019-04-11
@vbNoName

get user-first comment pairs

select
user_id, first_comment = min(created_at)
group by user_id

well, then either cte, or join, or select from this with a condition
where first_comment between _min_date_ and _max_date_

A
Alexander, 2019-04-11
@NeiroNx

SELECT u.id
FROM comments  c
LEFT JOIN users AS u ON u.id = c.user_id
WHERE c.created_at > to_timestamp('01.01.2019', 'DD.MM.YYYY') 
   AND c.created_at < to_timestamp('01.02.2019', 'DD.MM.YYYY')
GROUP BY u.id

Need to improve my writing skills...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question