Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting/casting output as integer in SQL

Tags:

sql

int

mysql

I'm working on a site that requires me to display a graph of the average number per day of a user input. I have a SQL query already that returns this info to me:

SELECT sum(number)/count(number) as average, date FROM stats WHERE * GROUP BY date 

This gives me the result I am looking for, but the result is given with three decimals precision. I want to round of this number. I could do it in PHP or my template engine, of course, but I was curious if there was a way to do this all in the database.

Is there a way to cast an output as an integer (in MySQL)?

like image 555
MrGlass Avatar asked Jan 17 '12 14:01

MrGlass


People also ask

Can SQL cast string to int?

CAST and CONVERT can be used to convert a string to a number of any data type. For example, you can convert a string to a number of data type INTEGER. TO_DATE converts a formatted date string to a date integer. TO_TIMESTAMP converts a formatted date and time string to a standard timestamp.

How do you select an integer in SQL?

SELECT CAST(sum(number)/count(number) AS UNSIGNED) as average... Or SIGNED if the SUM part can ever add up to a negative number. Show activity on this post. Use the DIV operator.

How do I cast as decimal in SQL?

Use the CAST() function to convert an integer to a DECIMAL data type. This function takes an expression or a column name as the argument, followed by the keyword AS and the new data type. In our example, we converted an integer (12) to a decimal value (12.00).


1 Answers

SELECT    CAST(sum(number)/count(number) as UNSIGNED) as average,    date  FROM stats  WHERE *  GROUP BY date 
like image 192
Oleg Dok Avatar answered Sep 23 '22 02:09

Oleg Dok