A
A
Artem2021-07-29 17:54:09
PostgreSQL
Artem, 2021-07-29 17:54:09

How to split the sample by periods?

fekqzncdgihhuzrmkpei06jugg4.png

I need a query that will allow me to get the number of documents owned by a counterparty by period: for 7 days, for 14 days, for a month, two

. At the moment, the following works for one period:

SELECT
  COUNT(dow.document_id) as "7 days",
  c.short_name
  FROM documents_owners dow
INNER JOIN contractors_main c ON dow.contractor_id = c.id
INNER JOIN documents_main d ON dow.document_id = d.id
WHERE d.created_at > NOW() - interval '7 days'
GROUP BY c.short_name
ORDER BY COUNT(dow.document_id) DESC


But I don’t want to write such a sheet for each period and then somehow combine them.
Tell me, how is this solved?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Slava Rozhnev, 2021-07-29
@proudmore

SELECT
  COUNT(case when d.created_at > NOW() - interval '7 days' then 1 else null end) as "7 days",
  COUNT(case when d.created_at > NOW() - interval '14 days' then 1 else null end) as "14 days",
  COUNT(case when d.created_at > NOW() - interval '1 month' then 1 else null end) as "1 month"
  c.short_name
  FROM documents_owners dow
INNER JOIN contractors_main c ON dow.contractor_id = c.id
INNER JOIN documents_main d ON dow.document_id = d.id
GROUP BY c.short_name
ORDER BY COUNT(dow.document_id) DESC

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question