Kevin Jensen Petersen
Kevin Jensen Petersen

Reputation: 513

SQL Server Subtract certain percent

I'm trying to subtract a certain percent of my price, into a AS columm.

SELECT TOP 2 *, price - (price * (discount/100)) AS discountedPrice 
FROM products 
WHERE discount != 0

But this seems not to work. What have I done wrong?

I want it like this, let's say price is 500 and discount is 20. Then it'll have to subtract those 20 as percent of the 500.

So 500 - 20%, just in SQL Server format.

Upvotes: 0

Views: 3221

Answers (3)

Tim Schmelter
Tim Schmelter

Reputation: 460138

I assume that discount is an int, then you should prepend a 1.0 to cast it to a floating point number.

price - (price * (1.0 discount/100))

Upvotes: 0

andy
andy

Reputation: 6079

Reference : Link

SELECT TOP 2 *, price - (price * (discount/100.0)) AS discountedPrice FROM 
products WHERE discount != 0

Upvotes: 0

podiluska
podiluska

Reputation: 51494

You're dividing integers : 20/100 is 0, not 0.2

Try making the division by 100.0

SELECT TOP 2 
*, 
price - (price * (discount/100.0)) AS discountedPrice 
FROM products 
WHERE discount != 0

If you want the discount price to be an int...

SELECT TOP 2 *, 
CONVERT(int, price - (price * (discount/100.0))) AS discountedPrice 
FROM products
WHERE discount != 0

Upvotes: 1

Related Questions