我需要将发票行分成(在这种情况下)3个部分(每个部分有2个小数位),但我必须确保所分割的总和等于原始值。
例如:如果我将5.13分别除以3%,42%和55%(均四舍五入为2DP),则最终得到:
0.15
2.82
2.15
Sum = 5.12.
我唯一能弄清楚该怎么做的方法是使用case语句并在除最后一行以外的所有内容上拆分为2DP。
对于最后一行,将所有先前值相加,然后从原始值中减去该值。这种方法需要一些子选择。我敢肯定,有更好的方法可以做到,但要空白。
(仅供参考,这是第三方供应商的产品,因此我必须从MONEY开始,然后将插入内容返回MONEY类型列,并且所有值都必须为2DP
这是我的示例:
DECLARE
@CurrExtPrice money = 5.13
DECLARE @tGLSplit AS TABLE
(
ID INT IDENTITY(1,1)
,GLCode NVARCHAR(50)
,PercentSplit DECIMAL(18, 2)
)
INSERT INTO @tGLSplit
([GLCode], [PercentSplit])
Select
'Split1', 0.03
UNION ALL
Select
'Split2', 0.55
UNION ALL
Select
'Split3', 0.42
-- Source Date
SELECT * FROM @tGLSplit [tgs]
SELECT
@CurrExtPrice AS OriginalValue
,tg.[PercentSplit]
,CAST(@CurrExtPrice * tg.[PercentSplit] AS DECIMAL(18,2)) AS Split2DP
,CASE
WHEN tg.ID < (SELECT MAX(ID) FROM @tGLSplit)
THEN
CAST(@CurrExtPrice * tg.[PercentSplit] AS DECIMAL(18,2))
ELSE
(SELECT @CurrExtPrice - SUM(CAST(@CurrExtPrice * [PercentSplit] AS decimal(18,2))) FROM @tGLSplit WHERE ID < (SELECT MAX(ID) FROM @tGLSplit) )
END AS NewSplitValue
FROM @tGLSplit tg
有人有魔术算法吗?
TIA
标记
最佳答案
这对我来说是成功的。在行级别上四舍五入到1000时产生的总和似乎在四舍五入到100时有效。清理并修改为您的特定需求。
IF OBJECT_ID('tempdb..#Temp') IS NOT NULL DROP TABLE #Temp
GO
DECLARE @Total MONEY = 5.13;
;WITH
SplitData AS
(
SELECT .03 AS SplitPercent
UNION
SELECT .42
UNION
SELECT .55 AS SplitPercent
),
Percents AS
(
SELECT S.SplitPercent,
@Total AS FullMoneyValue,
@Total * S.SplitPercent AS Total,
ROUND(@Total * S.SplitPercent,3,0) AS RoundedTotal
FROM SplitData AS S
)
SELECT P.*
INTO #Temp
FROM Percents AS P
SELECT SUM(P.Total), ROUND(SUM(P.RoundedTotal),2,0)
FROM #Temp AS P
关于sql - SQL-划分一个值,并确保它恢复为原始值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28943763/