October 20, 2010 at 8:24 am
CREATE TABLE #TblTemp( IdINT,
Price DECIMAL(18,9))
INSERT INTO #TblTemp
SELECT 1,10
INSERT INTO #TblTemp
SELECT 1,9999.9999
INSERT INTO #TblTemp
SELECT 2,15
INSERT INTO #TblTemp
SELECT 2,25
SELECT Id , avg(Price) AVGPrice from #TblTemp GROUP BY Id
Have a requirement to calculate average of a field but the average should be set to a constant when there is a specific value.
In the above script i would want the average for Id 1 to be 1111.1111 (Constant) when there is a price value of 9999.9999.
In other words whenever ther is a price of 9999.9999 for an id the average should be 1111.1111
Any help is appreciated. Thanks
October 20, 2010 at 1:37 pm
What would be your expected result if there are more than one row per id where either one row has the value 9999.9999 or all rows or sum = 9999.9999 or any other fany way?
Your sample code covers one possible scenario. But how about the other?
October 20, 2010 at 2:53 pm
Thanks for responding.
In the above example i want a result like this.
Id AvgPrice
1 1111.1111
2 20
If there is a record with a price of 9999.9999 for a specific id the avgprice for that id should show as 1111.1111
There could be other prices for that Id that are not 9999.9999 but i would still want to see 1111.1111 for that id.
If no rows has a price of 9999.9999 for an ID then price should be averaged.
October 20, 2010 at 3:06 pm
Something along those lines?
SELECT
id,
CASE
WHEN EXISTS (SELECT 1 FROM #TblTemp t2 WHERE t1.id=t2.id AND Price=9999.9999)
THEN 1111.1111
ELSE AVG(Price) END AVGPrice
FROM #TblTemp t1
GROUP BY Id
October 21, 2010 at 3:08 pm
Thats it! really appreicate your help on this.
Viewing 5 posts - 1 through 4 (of 4 total)
You must be logged in to reply to this topic. Login to reply