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 |
|
ddobbertin
Yak Posting Veteran
51 Posts |
Posted - 2007-04-06 : 15:41:07
|
| I know...sounds confusing, but it's not.I have a table in this format (underscores are just place holders for the forum):Shift - Points1_______51_______43_______9There are 4 work shifts 1-4, I need to get the average of points per shift. Simple query yes I know...however if there has not been data posted for a shift I still want the return to show the shift number and 0 for the average. So using the above table I would return the following:Shift - Average Points1_______4.52_______0.03_______94_______0.0Any and all help is appreciated! |
|
|
jsmith8858
Dr. Cross Join
7423 Posts |
Posted - 2007-04-06 : 15:53:14
|
| All you need is a left outer join, assuming you have a table of Shifts. If you don't have a table of Shifts, then you need one that defines shifts. If you have that, then all you need is something like this:select shifts.shift, isnull(avg(ShiftPoints.Points), 0) as AvgShiftPointsfrom shiftsleft outer join shiftPoints on shifts.shift = shiftPoints.shiftgroup by shifts.shift- Jeffhttp://weblogs.sqlteam.com/JeffS |
 |
|
|
ddobbertin
Yak Posting Veteran
51 Posts |
Posted - 2007-04-06 : 18:39:50
|
| So since I do not have a table of Shifts I should create one that uses it has a lookup table? Then when the join does not find anything that matches it will return the shift and a zero count?Any way of doing it without having a seperate table...maybe a CASE in the SELECT statement??? |
 |
|
|
cvraghu
Posting Yak Master
187 Posts |
Posted - 2007-04-06 : 19:08:56
|
| You can use derived table instead - select shifts.shift, isnull(avg(ShiftPoints.Points), 0) as AvgShiftPointsfrom ( select 1 as shift union select 2 union select 3 union select 4 ) shiftsleft outer joinshiftPoints on shifts.shift = shiftPoints.shiftgroup by shifts.shift |
 |
|
|
ddobbertin
Yak Posting Veteran
51 Posts |
Posted - 2007-04-06 : 19:17:41
|
| Awesome....I think that did it...Thanks cvraghu....dd |
 |
|
|
jsmith8858
Dr. Cross Join
7423 Posts |
Posted - 2007-04-06 : 21:14:04
|
| If Shifts are important to your database, you should simply create a shifts table. you can then have referential integrity, you can add any other attributes required to the Shifts table, and you can maintain Shifts simply by editing a table, and not editing your code.- Jeffhttp://weblogs.sqlteam.com/JeffS |
 |
|
|
|
|
|
|
|