Yii2 : How to write distinct SQL query?

JKLM picture JKLM · Jul 11, 2015 · Viewed 53.3k times · Source

I want to implement following SQL queries in Yii 2 but with no success.

This should give total number of unique company names:

SELECT count(DISTINCT(company_name)) FROM clients

And this should display company_name with client code and id(PK):

SELECT (DISTINCT(company_name,client_code)) FROM clients

How to achieve this?

Answer

Muhammad Shahzad picture Muhammad Shahzad · Dec 4, 2015

Try this:

$total = YourModel::find()->select('company_name')->distinct()->count();

In Search Model:

public function search($params)
{
    $query = YourModel::find()->select('company_name')->distinct();
    // or
    $query = YourModel::find()->select(['company_name', 'client_code'])->distinct();

    $query->orderBy('id desc');

    $dataProvider = new ActiveDataProvider([
        'query' => $query,
    ]);
    // ...
}