将组百分比计算为1位小数 - SQL

时间:2016-03-14 10:50:46

标签: mysql sql

我现在有这个SQL:

SELECT Count(create_weekday), 
   create_weekday, 
   Count(create_weekday) * 100 / (SELECT Count(*) 
                                  FROM   call_view 
                                  WHERE 
   ( create_month = Month(Now() - 
                    INTERVAL 1 month) ) 
   AND ( create_year = Year( 
         Now() - INTERVAL 1 month) ) 
   AND customer_company_name = "Company"
       ) AS Percentage
 FROM   call_view 
WHERE  ( create_month = Month(Now() - INTERVAL 1 month) ) 
   AND ( create_year = Year(Now() - INTERVAL 1 month) ) 
   AND customer_company_name = "Company" 
   GROUP BY CREATE_WEEKDAY
ORDER BY (CASE CREATE_WEEKDAY
WHEN 'Monday'   THEN 1
WHEN 'Tuesday'   THEN 2
WHEN 'Wednesday'   THEN 3
WHEN 'Thursday'   THEN 4
WHEN 'Friday'    THEN 5
WHEN 'Saturday'  THEN 6
WHEN 'Sunday' THEN 7
ELSE 100 END)

它正在工作,我收到了结果:

Count(create_weekday) | Create_Weekday | Percentage
225                       Monday          28.0899

如何舍入到小数点后1位?(如28.1)

非常感谢任何帮助

4 个答案:

答案 0 :(得分:0)

使用ROUND(百分比,1):

SELECT Count(create_weekday), 
   create_weekday, 
   ROUND(Count(create_weekday) * 100 / (SELECT Count(*) 
                                  FROM   call_view 
                                  WHERE 
   ( create_month = Month(Now() - 
                    INTERVAL 1 month) ) 
   AND ( create_year = Year( 
         Now() - INTERVAL 1 month) ) 
   AND customer_company_name = "Company"
       ), 1) AS Percentage
 FROM   call_view 
WHERE  ( create_month = Month(Now() - INTERVAL 1 month) ) 
   AND ( create_year = Year(Now() - INTERVAL 1 month) ) 
   AND customer_company_name = "Company" 
   GROUP BY CREATE_WEEKDAY
ORDER BY (CASE CREATE_WEEKDAY
WHEN 'Monday'   THEN 1
WHEN 'Tuesday'   THEN 2
WHEN 'Wednesday'   THEN 3
WHEN 'Thursday'   THEN 4
WHEN 'Friday'    THEN 5
WHEN 'Saturday'  THEN 6
WHEN 'Sunday' THEN 7
ELSE 100 END)

答案 1 :(得分:0)

您可以使用内置的ROUND(N,D)函数,第二个参数是位数。

MySQL参考:http://dev.mysql.com/doc/refman/5.7/en/mathematical-functions.html#function_round

答案 2 :(得分:0)

正如Jarlh所说,cast(Percentage as decimal(4,1))将此值设置为小数值,包含4个位置和1个小数位。 Percentage的列值将四舍五入为此条件。

答案 3 :(得分:0)

您有几种选择。我不建议使用round(),因为这并没有真正改变基础表示。

您可以使用format()将值转换为字符串,或者只是将值转换为小数/数字。这看起来像:

SELECT . . .
       CAST(Count(create_weekday) * 100 /
            (SELECT Count(*) 
             FROM call_view 
             WHERE (create_month = Month(Now() - INTERVAL 1 month) )  AND
                   (create_year = Year( Now() - INTRVAL 1 month) ) AND
                   customer_company_name = 'Company'
            ) as DECIMAL(4, 1)
           ) as Percentage