Saurabh Saurabh - 3 months ago 90
MySQL Question

Yii2 : How to write distinct sql query?

Want to implement following SQL queries in YII 2 but no success-

SELECT count(DISTINCT(company_name)) FROM clients


This should give total number of Unique Company Name

And

SELECT (DISTINCT(company_name,client_code)) FROM clients


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


how to achieve this?

Answer

Answering my own question I got following working solutions-

Got the count for Unique company_name,

$query = new Query;
    $my = (new yii\db\Query())
    ->select(['company_name',])
    ->from('create_client')
    ->distinct()
    ->count();
  echo $my;   

And list of distinct company_name and client_code by -

$query = new yii\db\Query();
            $data = $query->select(['company_name','client_code'])
        ->from('create_client')
        ->distinct()
        ->all();
        if($data) {
         foreach($data as $row)
        {
        echo 'company_name: ' . $row['company_name'] . ' client_code: ' . $row['client_code'] . '<br>';
            }
        }