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
 Case From In Statement Aggregate

Author  Topic 

mgonda
Starting Member

29 Posts

Posted - 2011-09-26 : 12:42:15
Is there a way to create a case statement from and aggregate function contained within the same select statement? Assume I have a table with books in it, and I have multiple books of the same title, but with different costs. I want to average prices for a distinct title, and then write a case that will create a column that says if the book is cheap, regular or expensive.

I know the following code doesn't work, but I think it may get my intentions across better than my words. What would be the best way to do this?

SELECT DISTINCT Title, AVG(Price) AS AvgPrice, Analysis = case
WHEN AvgPrice < 25 THEN 'Cheap'
WHEN AvgPrice BETWEEN 25 AND 50 THEN 'Regular'
ELSE 'Expensive' END
FROM TblBook

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2011-09-26 : 12:55:49
[code]
SELECT Title,AvgPrice,
Analysis = case
WHEN AvgPrice < 25 THEN 'Cheap'
WHEN AvgPrice BETWEEN 25 AND 50 THEN 'Regular'
ELSE 'Expensive'
END
FROM
(
SELECT Title, AVG(Price) AS AvgPrice
FROM TblBook
GROUP BY Title
)t
[/code]

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

mgonda
Starting Member

29 Posts

Posted - 2011-09-26 : 13:36:41
Thanks, I knew it had to be somethings simple like that, but it just wasn't coming to my head.
Go to Top of Page
   

- Advertisement -