如何让计算出的 SQL 服务器百分比值只显示两位小数?
How can I get my calculated SQL Server percentage value to only display two decimals?
我有这个 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”(等等)?
使用 ROUND 函数
SELECT ROUND(column_name,decimals) FROM table_name;
尝试在创建 table 时显式转换计算列,如下所示:
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))
);
我有这个 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”(等等)?
使用 ROUND 函数
SELECT ROUND(column_name,decimals) FROM table_name;
尝试在创建 table 时显式转换计算列,如下所示:
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))
);