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.
| 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 = caseWHEN AvgPrice < 25 THEN 'Cheap'WHEN AvgPrice BETWEEN 25 AND 50 THEN 'Regular'ELSE 'Expensive' ENDFROM TblBook |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2011-09-26 : 12:55:49
|
| [code]SELECT Title,AvgPrice,Analysis = caseWHEN AvgPrice < 25 THEN 'Cheap'WHEN AvgPrice BETWEEN 25 AND 50 THEN 'Regular'ELSE 'Expensive' ENDFROM (SELECT Title, AVG(Price) AS AvgPriceFROM TblBookGROUP BY Title)t[/code]------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/ |
 |
|
|
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. |
 |
|
|
|
|
|