4

I'm new with CakePHP 3 and I want to know how I can use a DISTINCT inside a COUNT such as the following SQL query.

SELECT `column_one`, COUNT(DISTINCT `column_two`) FROM `table` GROUP BY `column_one`

1 Answer 1

6

you can simply do

$query = $table->find()
->select([
    'column_one',
    'count' => "COUNT(DISTINCT `column_two`)"
])
->group(['column_one']);

but if you want to use cakephp sql function you can do

...
'count' => $query->func()->count('DISTINCT `column_two`')
....
Sign up to request clarification or add additional context in comments.

1 Comment

It would be a bit clearer if you included a complete solution using the native CakePHP count() function; it's not immediately obvious from your solution that $query needs to be instantiated separately. Like so: $query = $table->find('all'); $query = $query->select([ 'column_one', 'count' => $query->func()->count('DISTINCT column_two')]);

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.