选择查询:以十进制显示列的平均值

时间:2017-03-13 18:57:38

标签: sql sql-server

我希望在select查询中计算列值的平均值时得到十进制值。为此,我使用了以下查询。但价值来自3.0而不是3.6。那有什么解决方案吗?

SELECT P.ANSW_ONE,P.ANSW_TWO,P.ANSW_THREE,P.ANSW_FOUR,P.ANSW_FIVE, 
CAST(((P.ANSW_ONE+P.ANSW_TWO+P.ANSW_THREE+P.ANSW_FOUR+P.ANSW_FIVE)/5) AS DECIMAL(10,1)) AS ANSW_AVG 
FROM FEEDBACK P 

enter image description here

2 个答案:

答案 0 :(得分:1)

CAST整个SUM而不是结果,并使用5.0只是为了强制它是十进制而不是整数。

SELECT P.ANSW_ONE,
       P.ANSW_TWO,
       P.ANSW_THREE,
       P.ANSW_FOUR,
       P.ANSW_FIVE, 
       (CAST((P.ANSW_ONE+P.ANSW_TWO+P.ANSW_THREE+P.ANSW_FOUR+P.ANSW_FIVE) DECIMAL(10,1) /5.0)) AS ANSW_AVG 
FROM   FEEDBACK P 

答案 1 :(得分:0)

试试这个

SELECT 
  P.ANSW_ONE,
  P.ANSW_TWO,
  P.ANSW_THREE,
  P.ANSW_FOUR,
  P.ANSW_FIVE, 
  CAST(CAST(P.ANSW_ONE+P.ANSW_TWO+P.ANSW_THREE+P.ANSW_FOUR+P.ANSW_FIVE AS DECIMAL(10,1))/5 AS DECIMAL(10,1)) AS ANSW_AVG  
FROM FEEDBACK P 

在除以5之前投射总和,然后再次投射结果