Saturday, January 9, 2021

Transact-SQL percentage

DECLARE @t TABLE (id INT PRIMARY KEY, name VARCHAR(10), amount INT)
INSERT INTO @t VALUES (1,'apple',10)
INSERT INTO @t VALUES (2,'pear',20)
INSERT INTO @t VALUES (3,'plum',50)
SELECT 
t.id,
t.name,
t.amount,
CAST(t.amount AS FLOAT)/SUM(amount) OVER () AS [percent]
FROM @t t