如何将计算出的SQL Server百分比值仅显示两位小数?

时间:2016-01-18 17:59:46

标签: sql tsql precision decimal-precision

我有这个TSQL:

CREATE TABLE #TEMPCOMBINED(
  DESCRIPTION VARCHAR(200),
  WEEK1USAGE DECIMAL(18,2),
  WEEK2USAGE DECIMAL(18,2),
  USAGEVARIANCE AS WEEK2USAGE - WEEK1USAGE,
  WEEK1PRICE DECIMAL(18,2),
  WEEK2PRICE DECIMAL(18,2),
  PRICEVARIANCE AS WEEK2PRICE - WEEK1PRICE,
  PRICEVARIANCEPERCENTAGE AS (WEEK2PRICE - WEEK1PRICE) / NULLIF(WEEK1PRICE,0)
);

INSERT INTO #TEMPCOMBINED (DESCRIPTION, 
WEEK1USAGE, WEEK2USAGE, WEEK1PRICE, WEEK2PRICE)
SELECT T1.DESCRIPTION, T1.WEEK1USAGE, T2.WEEK2USAGE, 
T1.WEEK1PRICE, T2.WEEK2PRICE
FROM #TEMP1 T1
LEFT JOIN #TEMP2 T2 ON T1.MEMBERITEMCODE = T2.MEMBERITEMCODE

...按照我的意愿工作(显示" Usage"" Price"列)的两位小数值除了计算的百分比值(PRICEVARIANCEPERCENTAGE)显示值比Cyrano de Bergerac的鼻子更长,例如" 0.0252707581227436823"

我怎样才能强迫它改为" 0.03" (等等)?

3 个答案:

答案 0 :(得分:1)

使用ROUND函数

SELECT ROUND(column_name,decimals) FROM table_name;

答案 1 :(得分:1)

在创建表时尝试显式地转换计算列,如下所示:

CREATE TABLE #TEMPCOMBINED(
  DESCRIPTION VARCHAR(200),
  WEEK1USAGE DECIMAL(18,2),
  WEEK2USAGE DECIMAL(18,2),
  USAGEVARIANCE AS WEEK2USAGE - WEEK1USAGE,
  WEEK1PRICE DECIMAL(18,2),
  WEEK2PRICE DECIMAL(18,2),
  PRICEVARIANCE AS WEEK2PRICE - WEEK1PRICE,
  PRICEVARIANCEPERCENTAGE AS CAST((WEEK2PRICE - WEEK1PRICE) / NULLIF(WEEK1PRICE,0) AS DECIMAL(18,2))

);

答案 2 :(得分:1)

使用ROUND()函数。看看herehere