Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

398
Visualizações
Laravel get count of column rows with condition

Suppose if I have a table of

ID      Col1     Col2       Col3       Col4     Col5

1       Hello    ""         Hi          ""       ""
2       two      ""         Hi          here     ""

I want to get the count of Col(X) without including the empty column. So for record 1 I must have a count of 2 and for record 2 I have 3

How can I do it in MySQL or in Laravel's Eloquent or Query Builder? Thanks in advance.

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

What you want, is to sum the not empty fields. In MySQL it looks like:

SELECT *, SUM((Col1!='') + (Col2!='') + (Col3!='') + (Col4!='') + (Col5!='')) as NotEmptyFields 
FROM table 
GROUP BY ID;

In Laravel it looks like:

Model::select(DB::raw('*, SUM((Col1!="") + (Col2!="") + (Col3!="") + (Col4!="") + (Col5!="")) as NotEmptyFields'))
    ->groupBy('ID')
    ->get();
over 4 years ago · Santiago Trujillo Relatório

0

Try this solution:

$data = DB::table('MyTable')->get();

Get all data from table using query like this in laravel. It return array of objects. So iterate your array using for each loop and check the columns or empty or not.

If any column is empty do nothing.

But if any column has a value count+1 add in your result array.

$result = [];

foreach($data as $object)
{
    $result[$object->id] = 0;

    foreach($object as $key => $value) 
    {        
        if(!empty($value))
        {
            if($key != 'id')
            {
                $result[$object->id] = $result[$object->id] + 1;
            }
        }
    }
}

var_dump($result);
over 4 years ago · Santiago Trujillo Relatório

0

Muhammad answer could become real slow on big datasets.

Try like this.

DB::table('model')
    ->select(DB::raw('
        (is_null(Col1) OR Col1 = '') +
        (is_null(Col2) OR Col2 = '') +
        (is_null(Col3) OR Col3 = '') +
        (is_null(Col4) OR Col4 = '') +
        (is_null(Col5) OR Col5 = '') 
            as NumberofNulls'
    ))

This should now count columns with either NULL or empty string in them

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda