Jump to content

Transact-SQL Cast or Convert

Go to solution Solved by adman29,

Okay, I figured it out, sorry for the quick turnaround, but if anyone needs the info for future reference:

Select P.ProductModelID, P.Name, CAST(((P.ListPrice - P.StandardCost)/P.StandardCost) AS DECIMAL(18,2)) AS ProfitMargin
From Production.Product P
Left JOIN Production.ProductSubcategory PS
		ON P.ProductSubcategoryID = PS.ProductSubcategoryID
Right Join Production.ProductCategory PC
		ON PC.ProductCategoryID = PS.ProductCategoryID
Where PC.ProductCategoryID = 1
ORDER BY ProfitMargin DESC

 

Hey Y'all,

I've been working on a SQL Project and I missed the lesson on Cast and Convert

Would anyone know how to Cast a calculated field into a decimal that has only 2 decimal places?

 

My current code is basically:

SELECT P.ProductID, P.Name, (P.ListPrice-P.StandardPrice)/P.StandardPrice AS Profit Margin
FROM Produciton.Product P
//A whole bunch of Joins down here)

Lemme know if you have questions

Link to comment
https://linustechtips.com/topic/1115926-transact-sql-cast-or-convert/
Share on other sites

Link to post
Share on other sites

Okay, I figured it out, sorry for the quick turnaround, but if anyone needs the info for future reference:

Select P.ProductModelID, P.Name, CAST(((P.ListPrice - P.StandardCost)/P.StandardCost) AS DECIMAL(18,2)) AS ProfitMargin
From Production.Product P
Left JOIN Production.ProductSubcategory PS
		ON P.ProductSubcategoryID = PS.ProductSubcategoryID
Right Join Production.ProductCategory PC
		ON PC.ProductCategoryID = PS.ProductCategoryID
Where PC.ProductCategoryID = 1
ORDER BY ProfitMargin DESC

 

Link to post
Share on other sites

On 10/21/2019 at 10:17 AM, adman29 said:

Okay, I figured it out, sorry for the quick turnaround, but if anyone needs the info for future reference:


Select P.ProductModelID, P.Name, CAST(((P.ListPrice - P.StandardCost)/P.StandardCost) AS DECIMAL(18,2)) AS ProfitMargin
From Production.Product P
Left JOIN Production.ProductSubcategory PS
		ON P.ProductSubcategoryID = PS.ProductSubcategoryID
Right Join Production.ProductCategory PC
		ON PC.ProductCategoryID = PS.ProductCategoryID
Where PC.ProductCategoryID = 1
ORDER BY ProfitMargin DESC

 

If it turns out you need standard thousand separators as well, you can use CAST to money datatype within a CONVERT like so:

 

SELECT convert(varchar,cast(((P.ListPrice - P.StandardCost)/P.StandardCost) as money), 1) as 'ProfitMargin'

 

However, once converted to varchar, you lose the ability to perform calculations. So this is more for presentation purposes - don't convert out of an INT datatype until you're done performing calculations.

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×