sql - How to get AVG in CASE with condition? -


i have table integer values. negative, 0, positive , null. need treat null 0, calculate average given date , if average value less 0 put 0 there.

my query following:

select     id,      valuedate,     case          when avg(isnull(value, 0)) > 0 avg(isnull(value, 0))         else 0     end avgvalue sometable valuedate = @givendate group id, valuedate 

how avoid double aggregate function definition in case statement (aggregate statement more complex)?

this solution without creating implementation of not build-in functions. know example more complex idea:

create table datasource (     [id] tinyint    ,[value] int )  insert datasource ([id], [value]) values (1, 2)       ,(1, 0)       ,(1, null)       ,(1, 98)       ,(1, null)       ,(2, -4)       ,(2, 0)       ,(2, 0)       ,(2, null)  select [id]       ,max([value]) (   select  [id]          ,avg(coalesce([value],0))   datasource   group [id]   union   select distinct [id]                  ,0   datasource ) data([id],[value]) group [id] 

here fiddle - http://sqlfiddle.com/#!6/3d223/14


Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -