错误的百分比已应用于字段(TotalPercentageAmount),我需要更正它。 给定2个字段Amount和TotalPercentageAmount如何计算应用的百分比? 我需要计算应用于TotalPercentageAmount的百分比,并使用正确的百分比更新列。
我创建的小脚本用于模仿我的场景。创建的表包含错误的TotalPercentageAmount !!!
CREATE TABLE [dbo].[SalesReportTest](
[Id] [int] NOT NULL,
[Amount] [decimal](18, 4) NOT NULL,
[TotalPercentageAmount] [decimal](18, 4) NOT NULL,
CONSTRAINT [PK_SalesReportTest] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET NOCOUNT ON;
SET XACT_ABORT ON;
GO
BEGIN TRANSACTION;
INSERT INTO [dbo].[SalesReportTest]([Id], [Amount], [TotalPercentageAmount])
SELECT 1, 55.0000, 52.0300 UNION ALL
SELECT 2, 440.0000, 416.2200 UNION ALL
SELECT 3, 300.0000, 283.8000 UNION ALL
SELECT 4, -55.0000, -52.0300 UNION ALL
SELECT 5, 98.0000, 92.7000 UNION ALL
SELECT 6, -10.0000, -9.4600
COMMIT;
RAISERROR (N'[dbo].[SalesReportTest]: Insert Batch: 1.....Done!', 10, 1) WITH NOWAIT;
GO
答案 0 :(得分:1)
您可以尝试以下方法来确定使用的百分比。但是,似乎存在一些精度损失,因为Amount列似乎被截断。我还包括一个用于演示样本数据中5.72%calc的列。
SELECT *,
CAST ((Amount / TotalPercentageAmount - 1) * 100 AS DECIMAL (5, 2)) as Pct,
CAST (TotalPercentageAmount * 1.0572 AS INT) Amt_Calc
FROM [SalesReportTest]
答案 1 :(得分:0)
如果我理解正确,您可以更新百分比,如:
update SalesReportTest
set TotalPercentageAmount = Amount /
(select sum(amount) from SalesReportTest)