S
S
seropaski2015-12-23 17:43:42
MySQL
seropaski, 2015-12-23 17:43:42

SQL query to count unique values?

There is a database with camp, random_id, action records. camp can be repeated, as can random_id. action takes only two values ​​0\1. We need to extract the number of unique random_ids for each of the action values ​​(0/1) and their corresponding camp. Group the output by camp.
Which I just haven't tried. You can simply calculate the unique random_id for each of the action values ​​separately with the query

SELECT camp, COUNT(DISTINCT random_id) FROM table WHERE action = 0 group by camp

But for everything to be calculated in the aggregate, it does not work out in any way. Final request
SELECT camp, SUM(IF(action = '0', 1, 0)) as uniq_null, SUM(IF(action = '1', 1, 0)) as uniq_one FROM (SELECT DISTINCT camp, random_id FROM table) t GROUP BY camp

gives an error message
#1054 - Unknown column 'action' in 'field list'

Or
SELECT camp, SUM(IF(action = '0', 1, 0)) as uniq_null, SUM(IF(action = '1', 1, 0)) as uniq_one FROM table GROUP BY camp

But such a query produces the number of NOT unique values.
Does anyone have any suggestions on how to get the necessary data with one request?
SOLUTION OF THE PROBLEM:
SELECT camp, COUNT( DISTINCT random_id), action FROM table group by camp, action

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Kovalsky, 2015-12-23
@seropaski

SELECT camp, random_id,COUNT(1) FROM table WHERE action = 0 group by camp,randomId

So try.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question