I'm working to get some practice with SQL functions which are often used in a financial setting, and I created this simple table with products, prices and tax rates basically.
I then wrote a query to simulate a purchase invoice type of result set (I realize things like that are most often done at application level, or as a separate DB transaction).
After I wrote this query, I found myself using so many parentheses for operations, and repeating the same formulas over and over, and I thought; there's got to be a better way to do this! So here I am seeking peer review.
You can try it using SEDE.
Here is the table:
CREATE TABLE #Sales (
Id INT NOT NULL IDENTITY PRIMARY KEY
, Product NVARCHAR(MAX)
, Price DECIMAL(6,2)
, Qty INT
, Import BIT
, SalesTaxRate DECIMAL(6,2)
, ImportTaxRate DECIMAL(6,2)
);
GO
INSERT INTO #Sales (Product, Price, Qty, Import, SalesTaxRate, ImportTaxRate)
VALUES
('Apple Pie', 3.99, 10, 0, 7.50, NULL)
, ('Swiss Chocolate', 6.99, 5, 1, NULL, 5.50)
, ('French Wine', 12.99, 3, 1, 7.50, 5.50)
, ('Complimentary Gift', NULL, 1, 0, NULL, NULL)
;
GO
And here is the query which results in this table being returned:
SELECT
Id
, Product
, [Price] = COALESCE(Price, 0)
, Qty
, [Subtotal] = (ISNULL(Price,0) * Qty)
, [Sales Tax] = CAST((ISNULL(SalesTaxRate,0) * ISNULL(Price,0) * Qty) / 100 AS DECIMAL(6,2))
, [Import Tax] = CAST((ISNULL(ImportTaxRate,0) * ISNULL(Price,0) * Qty) / 100 AS DECIMAL(6,2))
, [Total Tax] = COALESCE(
CAST(((ISNULL(SalesTaxRate,0) * (ISNULL(Price,0) * Qty)) + (ISNULL(ImportTaxRate,0) * (ISNULL(Price,0) * Qty))) / 100 AS DECIMAL(6,2))
, 0)
, [Line Total] = (
ISNULL(Price,0) * Qty -- Subtotal
+ COALESCE(
CAST(((ISNULL(SalesTaxRate,0) * (ISNULL(Price,0) * Qty)) + (ISNULL(ImportTaxRate,0) * (ISNULL(Price,0) * Qty))) / 100 AS DECIMAL(6,2))
, 0)) -- Total Tax
FROM #Sales
UNION
SELECT
NULL
, 'Totals'
, NULL
, NULL
, SUM((ISNULL(Price,0) * Qty)) -- Subtotal
, SUM(CAST((ISNULL(SalesTaxRate,0) * ISNULL(Price,0) * Qty) / 100 AS DECIMAL(6,2)))
, SUM(CAST((ISNULL(ImportTaxRate,0) * ISNULL(Price,0) * Qty) / 100 AS DECIMAL(6,2)))
, SUM(COALESCE(
CAST(((ISNULL(SalesTaxRate,0) * (ISNULL(Price,0) * Qty)) + (ISNULL(ImportTaxRate,0) * (ISNULL(Price,0) * Qty))) / 100 AS DECIMAL(6,2))
, 0))
, SUM(
ISNULL(Price,0) * Qty -- Subtotal
+ COALESCE(
CAST(((ISNULL(SalesTaxRate,0) * (ISNULL(Price,0) * Qty)) + (ISNULL(ImportTaxRate,0) * (ISNULL(Price,0) * Qty))) / 100 AS DECIMAL(6,2))
, 0)) -- Total Tax
FROM #Sales