V
V
Vladimir2017-09-04 15:26:04
PostgreSQL
Vladimir, 2017-09-04 15:26:04

How to count the number of customers who bought in one store, and from a certain date made a purchase in another?

There is a table of users and a table of orders. There is a field in the orders table: store ID. It is necessary to count the number of users who until 2016 made all purchases only in the store id=1, and since 2016 made at least one purchase in any other store id != 1.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2017-09-04
Kharseev @vkharseev

SELECT count(*)
FROM users u
WHERE
  u.id IN ((
    SELECT o.user_id
    FROM orders o
    WHERE
      o.date < '2016-01-01' AND
      o.shop_id = 1 AND
      o.user_id NOT IN (SELECT user_id FROM orders WHERE shop_id <> 1 AND date < '2016-01-01')
  ) INTERSECT (
    SELECT o.user_id
    FROM orders o
    WHERE o.date >= '2016-01-01' AND o.shop_id <> 1
  ));

S
shushpanio, 2017-09-04
@shushpanio

I will write an algorithm. Request I think on it write (in SQL I can confuse). 1. get a list of
users whose store id=1 and Distinct count (id)=1 for the period <=2016 (there was only a store with ID=1)
records with ID<>1

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question