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 |
|
jeffbond
Starting Member
16 Posts |
Posted - 2008-10-24 : 08:21:19
|
| Hi,I have a table with 2 columns: item & priceitem contains : bread, meat, cheese, beverage price contains : 2, 6, 1, 4I need to know the average price per item type (beverage or food) an example of resultset would be:Food 3Beverage 4What would be the SQL query for this? |
|
|
GilaMonster
Master Smack Fu Yak Hacker
4507 Posts |
Posted - 2008-10-24 : 08:34:45
|
| Do you have a table somewhere that defines what item is what type?--Gail ShawSQL Server MVP |
 |
|
|
jeffbond
Starting Member
16 Posts |
Posted - 2008-10-24 : 08:46:17
|
| Nope.I decide the tytpe manually in my queryanything that is not beverage is food.here is an example of what the item table contains :name pricebread 2meat 6cheese 1coke 4I need the average price grouped by food and beverage:With records above, my result set should be as follow. what is the sql for it?food 3beverage 4 |
 |
|
|
sodeep
Master Smack Fu Yak Hacker
7174 Posts |
Posted - 2008-10-24 : 08:54:18
|
| select case when item in ('coke'.....) then 'Beverages' else 'Food' end as [name],avg(price) as pricefrom tablegroup by case when item in ('coke') then 'Beverages' else 'Food' endorder by price |
 |
|
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2008-10-24 : 10:17:06
|
[code]DECLARE @Sample TABLE ( Item VARCHAR(20), Price SMALLMONEY )INSERT @SampleSELECT 'bread', 2 UNION ALLSELECT 'meat', 6 UNION ALLSELECT 'cheese', 1 UNION ALLSELECT 'beverage', 4SELECT CASE Item WHEN 'beverage' THEN Item ELSE 'food' END, AVG(Price)FROM @SampleGROUP BY CASE Item WHEN 'beverage' THEN Item ELSE 'food' END[/code] E 12°55'05.63"N 56°04'39.26" |
 |
|
|
|
|
|
|
|