Selecting/casting output as integer in SQL

后端 未结 5 1482
野的像风
野的像风 2020-12-14 16:01

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:

         


        
相关标签:
5条回答
  • 2020-12-14 16:32

    The valid types for a CAST in MySQL are as follows

    • BINARY[(N)]
    • CHAR[(N)]
    • DATE
    • DATETIME
    • DECIMAL[(M[,D])]
    • SIGNED [INTEGER]
    • TIME
    • UNSIGNED [INTEGER]

    So you could use

    SELECT CAST(sum(number)/count(number) AS UNSIGNED) as average...
    

    Or SIGNED if the SUM part can ever add up to a negative number.

    0 讨论(0)
  • 2020-12-14 16:33
    SELECT 
      CAST(sum(number)/count(number) as UNSIGNED) as average, 
      date 
    FROM stats 
    WHERE * 
    GROUP BY date
    
    0 讨论(0)
  • 2020-12-14 16:35

    Use the DIV operator.

    mysql> SELECT 5 DIV 2;
        -> 2
    

    Integer division. Similar to FLOOR(), but is safe with BIGINT values. Incorrect results may occur for noninteger operands that exceed BIGINT range.

    0 讨论(0)
  • 2020-12-14 16:48

    how about using MySQL FORMAT Function?

    mysql> SELECT FORMAT(12345.123456, 4);
    +-------------------------+
    | FORMAT(12345.123456, 4) |
    +-------------------------+
    | 12,345.1235             |
    +-------------------------+
    1 row in set (0.00 sec)
    
    mysql> SELECT FORMAT(12345.123456, 0);
    +-------------------------+
    | FORMAT(12345.123456, 0) |
    +-------------------------+
    | 12,345                  |
    +-------------------------+
    1 row in set (0.00 sec)
    
    0 讨论(0)
  • 2020-12-14 16:52
    SELECT convert(int, sum(number)/count(number)) as average,
      date
    FROM stats
    WHERE * GROUP BY date
    

    or

    SELECT 
      CAST(sum(number)/count(number) as INT) as average, 
      date 
    FROM stats 
    WHERE * 
    GROUP BY date
    
    0 讨论(0)
提交回复
热议问题