Convert Varchar to Int

Asked

Viewed 490 times

1

I need to perform a sub query in Query but the data types of the columns are different. I am using the structure below but it is in error :

SELECT MIN(POPULACAO), nome_mun from cidades
select CAST(populacao AS varchar (50) ) FROM cidades
where nome_mun= ( SELECT MIN(POPULACAO) from cidades)
group by nome_mun,populacao

I need to bring only the municipality with the smallest number of inhabitants of the table. If someone suggests a simpler Query.

If I use only the SELECT MIN(POPULACAO), name_mun from cities group by name_mun it brings the whole table . Within the population table has the type Int and name_mun varchar (50). Actually this type of conversion in Sql leaves me a little confused rs.

1 answer

1

But nome_mun is varchar and is the name of the municipality right? Can not equal min(populacao), which is numerical and has no relation to the name, so you need to return the nome_mun in the subquery, and calculate the min outside the select.

How are you using group by, can do this using having, thus:

SELECT   Cast(populacao AS VARCHAR (50) ) 
FROM     cidades 
WHERE    nome_mun= 
         ( 
                SELECT nome_mun 
                FROM   cidades) 
GROUP BY nome_mun 
HAVING   populacao = MIN(populacao))

This will return the name, where the population is the lowest value

  • Now it makes sense. Thank you very much.

Browser other questions tagged

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