Get only first word within a sql server query

Asked

Viewed 7,623 times

2

Good afternoon to you I have the following query

SELECT COUNT (SolID) as quant, UsuNome as gerador 
FROM Solicitacao 
INNER JOIN Usuario ON Solicitacao.UsuIDAtendenteViaFone = Usuario.UsuID
WHERE UsuIDGrupo = 2655
AND DATEPART(m, SolData) = DATEPART(m, DATEADD(m, 0, getdate()))
AND DATEPART(yyyy, SolData) = DATEPART(yyyy, DATEADD(m, 0, getdate()))
GROUP BY UsuNome order by quant desc 

This query returns me this: inserir a descrição da imagem aqui

I need the generator column to return only the first name.

1 answer

7

It’s not much of a secret:

SELECT COUNT (SolID) as quant, 
    SUBSTRING(UsuNome, 1, CHARINDEX(' ', UsuNome, 1) - 1) as gerador 
FROM Solicitacao 
    INNER JOIN Usuario ON Solicitacao.UsuIDAtendenteViaFone = Usuario.UsuID 
WHERE UsuIDGrupo = 2655 
  AND DATEPART(m, SolData) = DATEPART(m, DATEADD(m, 0, getdate())) 
  AND DATEPART(yyyy, SolData) = DATEPART(yyyy, DATEADD(m, 0, getdate())) 
GROUP BY UsuNome 
order by quant desc

Explaining:

SUBSTRING(UsuNome, 1, CHARINDEX(' ', UsuNome, 1) - 1)

The first argument is the column itself. The second is the beginning of substring, and the third is the end of string, which use the function CHARINDEX to find the first occurrence of a space.

  • 2

    Thanks man, it’s really inexperienced, hehehehe

Browser other questions tagged

You are not signed in. Login or sign up in order to post.