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
 Calculation Help

Author  Topic 

Grifter
Constraint Violating Yak Guru

274 Posts

Posted - 2013-11-29 : 10:30:23
Hi
I am trying to calculate an average within a query:


coalesce(field1, 0) + coalesce(field2], 0) + coalesce(field3, 0)/Count [AVG]


It seems to be subtracting the value of field3 from the total of 3 fields at some points instead of giving me the average.

Some of the results are here:


Count Field1 Field2 Field3 Total Average
===== ====== ====== ====== ===== =======
2 NULL 6 NULL 6 6
11 NULL 28 13 41 29
10 NULL 33 NULL 33 33
3 NULL 12 NULL 12 12
48 NULL 108 1 109 108
7 NULL 25 NULL 25 25
1 NULL 1 NULL 1 1
3 NULL 13 NULL 13 13
141 1 1005 247 1253 1007
8 NULL 21 11 32 22
10 NULL 31 17 48 32
13 NULL 81 43 124 84
15 1 41 NULL 42 42
1 NULL 2 NULL 2 2
24 NULL 105 41 146 106
9 NULL 44 2 46 44
33 NULL 93 NULL 93 93


thanks for any input on how I may fix

G

khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2013-11-29 : 10:52:31
[code](coalesce(field1, 0) + coalesce(field2], 0) + coalesce(field3, 0))/Count [AVG][/code]


KH
[spoiler]Time is always against us[/spoiler]

Go to Top of Page

Grifter
Constraint Violating Yak Guru

274 Posts

Posted - 2013-11-29 : 11:44:52
Get this:

quote:
Msg 102, Level 15, State 1, Line 19
Incorrect syntax near ','.
Msg 102, Level 15, State 1, Line 27
Incorrect syntax near 'c'.


Can't see what's wrong?

coalesce((cte.Field1, 0) + coalesce(cte.Field2, 0) + coalesce(cte.Field3, 0))/cte.Count [AVG]


Also using cross apply in query:

cross apply
(
select cast(nullif(cte.Field1,0) as decimal(10, 2)) union all
select cast(nullif(cte.Field2,0) as decimal(10, 2)) union all
select cast(nullif(cte.Field3,0) as decimal(10, 2))
) c(sum2)
group by DiagnosisDesc,Count, [RAH22-23 Stay], [POST RAH22-23 Stay], [PRE RAH22-23 Stay]
Go to Top of Page

nigelrivett
Master Smack Fu Yak Hacker

3385 Posts

Posted - 2013-11-29 : 12:25:01
Bracket in the wrong place
(coalesce(cte.Field1, 0) + coalesce(cte.Field2, 0) + coalesce(cte.Field3, 0))/cte.Count [AVG]

==========================================
Cursors are useful if you don't know sql.
SSIS can be used in a similar way.
Beer is not cold and it isn't fizzy.
Go to Top of Page

Grifter
Constraint Violating Yak Guru

274 Posts

Posted - 2013-12-02 : 09:19:07
quote:
Bracket in the wrong place
(coalesce(cte.Field1, 0) + coalesce(cte.Field2, 0) + coalesce(cte.Field3, 0))/cte.Count [AVG]


Can't believe I missed that - thanks!

Go to Top of Page
   

- Advertisement -