我正在努力尝试获取一个SQL查询,只显示两位小数。不幸的是,它是一个非常复杂的查询和"十进制(18,2)"的每个组合。我试过的不起作用。
SELECT DISTINCT
Company_Name AS Company, CASE WHEN isnull((CAST(IsNull(SUM(Margin), 0) / CASE isnull(SUM(invoiceamt), 0) WHEN 0 THEN 1 ELSE SUM(invoiceamt)
END * 100 AS decimal(18, 2)) / 70), 0) < 0 THEN 0 ELSE (CAST(IsNull(SUM(Margin), 0) / CASE isnull(SUM(invoiceamt), 0)
WHEN 0 THEN 1 ELSE SUM(invoiceamt) END * 100 AS decimal(18, 2)) / 70) END * 100 AS Service_Goal
FROM v_cbi_Agr_Mo_Billing_History3
WHERE (1 = 1) AND (dbo.udf_cbi_InternalCompanyName() <> Company_Name) AND (DATEDIFF(mm, GETDATE(), MonthStart) BETWEEN 0 AND 0) AND
(AGR_Type_Desc IN ('Agreement1', 'Agreement2', 'Agreement3'))
GROUP BY Company_Name
HAVING (SUM(Margin) <> 0) OR
(SUM(InvoiceAmt) <> 0)
ORDER BY Company
答案 0 :(得分:1)
问题是您将此块作为小数转换然后除以70,这会产生更多的小数位。
Cast(Isnull(Sum(@margin), 0) / CASE Isnull(Sum(@invoiceamt), 0)
WHEN 0 THEN 1
ELSE Sum(@invoiceamt)
END * 100 AS DECIMAL(18, 2))
您可以将其更改为执行所有calulcations的操作,然后将其转换为小数(10,2)。我不确定你是怎么想要这一切的。
Cast(Isnull(Sum(@margin), 0) / CASE Isnull(Sum(@invoiceamt), 0)
WHEN 0 THEN 1
ELSE Sum(@invoiceamt)
END * 100 / 70 AS DECIMAL(18, 2))
答案 1 :(得分:0)
尝试将表达式的结果转换为所需的精度。 (内部强制转换用于避免整数除法)。
例如:
select
cast( 100 / cast(77 as decimal(10,2) ) as decimal(10,2) ),
100/cast(77 as decimal(10,2))
输出:
--------------------------------------- ---------------------------------------
1.30 1.29870129870