0

I have this :

CREATE TABLE tickets(id serial PRIMARY KEY, source text NOT NULL, user_id int NOT NULL, shop_id int NOT NULL, created_at time DEFAULT current_time);
INSERT INTO tickets VALUES (0, 'web-mobile', 1, 2);
INSERT INTO tickets VALUES (1, 'web-destkop', 1, 2);
INSERT INTO tickets VALUES (2, 'web-destkop', 2, 2);

SELECT shop_id, source, COUNT(DISTINCT(user_id)) AS user_count
FROM tickets
WHERE shop_id = 2
GROUP BY shop_id, source;

Rexster : http://rextester.com/TDS9913

But what I would like is to get the sum of distinct user_id on web-*.

shop_id source  user_count
2       web     2
1
  • 2
    Unrelated, but: distinct is NOT a function. count(distinct user_id) is sufficient Nov 14, 2017 at 11:25

2 Answers 2

4

You need to group by a substring of source:

SELECT shop_id, 
       substring(source,1,3), 
       COUNT(DISTINCT user_id) AS user_count
FROM tickets
WHERE shop_id = 2
GROUP BY shop_id, substring(source,1,3);

http://rextester.com/EFZZSG27212

5
  • Is it possible to do the same but more declarative ? Like mentioning 'web-mobile' and 'web-desktop' ? I tried using case statement but without success
    – Mio
    Nov 14, 2017 at 12:01
  • @Mio: do you mean where source in ('web-mobile', 'web-desktop') instead of where shop_id = 2? Nov 14, 2017 at 12:04
  • Sorry. Replace substring with something that mention 'web-mobile', 'web-desktop'
    – Mio
    Nov 14, 2017 at 12:07
  • If you're aggregating you have to "lose" some information!
    – Vérace
    Nov 14, 2017 at 12:34
  • I wrote an other related answer/question here : dba.stackexchange.com/questions/190876/…
    – Mio
    Nov 14, 2017 at 13:08
0

What you want is something like:

SELECT   
  shop_id, 
  user_id,  
  COUNT(user_id)  AS user_count, 
  LEFT(source, 4) AS new_source
FROM tickets
GROUP BY (user_id, shop_id, new_source)
ORDER BY user_id;

Result: (check the db-fiddle here)

shop_id     user_id     user_count  new_source
      2           1              2        web-
      2           2              1        web-

Of course you can use SUBSTRING instead of LEFT as suggested.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.