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 |
|
SQLCode
Posting Yak Master
143 Posts |
Posted - 2004-05-06 : 09:47:00
|
| I need help for the following.I have a tableTableACol1, Col2, Category, Date, TypeI am doingSelect Avg(Col1) Avrg, Sum(Col2) TotNum, CategoryFROM AWhere Date= somedateAND Type=sometype.Group by CategoryThe result isAvrg TotNum Category6.7 500 C1With these conditions I am only getting one category's data.I want to make the other categories as 0 if there is no data but I want the rest of the categories to show up too.The result should beAvrg TotNum Category6.7 500 C10 0 C20 0 C30 0 C40 0 C5I tried doing union as follows but the problem is it will have dupls.Select Category, Avg(Col1) Avrg, Sum(Col2) TotNumFROM TableAWhere Date=somedateAND Type=sometypeGROUP by Categoryunion allSelect distinct Category,0 as Avrg, 0 as TotNumFROM TableAIs there any better way than for me to do sub queries and unions?Looks like a simplest thing to do, but I can't think of a SIMPLER solution.Any advices please ?TIA |
|
|
LarsG
Constraint Violating Yak Guru
284 Posts |
Posted - 2004-05-06 : 11:12:37
|
| [code]Select Avg(case when Date = Somedate and type = sometype then Col1else 0 end) Avrg, Sum(case when date = somedate and type = sometype then Col2else 0 end) TotNum, CategoryFROM AGroup by Category[/code] |
 |
|
|
|
|
|
|
|