Catch only first word inside a sql server query

2

Good afternoon, 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:

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

    
asked by anonymous 03.11.2015 / 19:50

1 answer

7

There is not much 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 the substring , and the third is the end of string , which uses the CHARINDEX function to find the first occurrence of a space.

    
03.11.2015 / 19:55