Calculate Percentage Applied Sql server 2008
A wrong percentage has been applied to a field (TotalPercentageAmount) and I need to correct it. Given 2 fields Amount and TotalPercentageAmount how can I calculate what percentage was applied? I need to work out percentage applied to TotalPercentageAmount and UPDATE the column with correct percentage.
Little script I have created to mimin my scenario . Table created contains wrong 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
You can try the following to determine the percentage used. However, it appears that there is some precision loss because the Amount column appears to be truncated. I also include a column that demonstrates the 5.72% calc in your sample data.
SELECT *,
CAST ((Amount / TotalPercentageAmount - 1) * 100 AS DECIMAL (5, 2)) as Pct,
CAST (TotalPercentageAmount * 1.0572 AS INT) Amt_Calc
FROM [SalesReportTest]
If I understand you correctly, you can update the percentages like:
update SalesReportTest
set TotalPercentageAmount = Amount /
(select sum(amount) from SalesReportTest)
精彩评论