Mid
Window Functions
SQL & Databases
Write a query to calculate percentage of total using window functions.
Short answer: Divide each Amount by SUM(Amount) OVER () and multiply by 100. Cast carefully to avoid integer division.
Sample solution
T-SQL
SELECT ProductId, Amount,
CAST(100.0 * Amount / SUM(Amount) OVER () AS DECIMAL(5,2)) AS PctOfTotal
FROM Sales;
Use 100.0 (not 100) to force decimal math.
Share this Q&A
Share preview image: https://www.toolliyo.com/images/toolliyo-logo.png