Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Nested Select with Cast and Sum

Author  Topic 

richardlaw
Yak Posting Veteran

68 Posts

Posted - 2012-07-19 : 16:32:38
Hi

I'm trying to do some simple maths (quantity * price), but I need to nest a select to get the quantity, then cast it to a decimal. I think I close, but I just can't get it to work:

SELECT     Stock_ClubID, StockID, Stock_UsedItem, Stock_Title, Stock_SellPrice, Stock_Cost, Stock_DisplayInShop,
SUM((CAST(((SELECT COUNT(*) AS Expr1
FROM dbo.tbl_StockControl_GroupItems
WHERE (Stock_GroupItem_StockID = dbo.tbl_StockControl.StockID)) AS Quantity) as DECIMAL(5,2)) as Total) * (CAST(Stock_SellPrice as DECIMAL(5,2))) AS Total_SellPrice
FROM dbo.tbl_StockControl


Any ideas?

Thanks in advance

sunitabeck
Master Smack Fu Yak Hacker

5155 Posts

Posted - 2012-07-19 : 21:04:13
You can use the APPLY operator (if you are on SQL 2005 or higher) or a subquery. Using APPLY, it would be like this:
SELECT a.Stock_ClubID,
a.StockID,
a.Stock_UsedItem,
a.Stock_Title,
a.Stock_SellPrice,
a.Stock_Cost,
a.Stock_DisplayInShop,
b.Expr1 * CAST(Stock_SellPrice AS DECIMAL(5, 2)) AS Total_SellPrice
FROM
dbo.tbl_StockControl AS a
OUTER APPLY
(
SELECT COUNT(*) AS Expr1
FROM dbo.tbl_StockControl_GroupItems AS c
WHERE (c.Stock_GroupItem_StockID = a.StockID)
) AS b;
Go to Top of Page

richardlaw
Yak Posting Veteran

68 Posts

Posted - 2012-07-20 : 02:17:51
Fantastic, works perfectly! Thank you for taking the time to write that out - very much appreciated.
Go to Top of Page

sunitabeck
Master Smack Fu Yak Hacker

5155 Posts

Posted - 2012-07-20 : 07:44:10
You are welcome, glad to be of help.)
Go to Top of Page
   

- Advertisement -