SparkyP
asked on
Average of Best 3
I want to cost refrigerant based on the average of the best 3 prices from suppliers for each type of refrigerant.
I am using the following to get the best 3, but how would I then get the average per type?
SELECT TOP (100) PERCENT Type, Supplier, Cost, ID
FROM dbo.RefrigerantPricing
WHERE ((SELECT COUNT(*) AS Expr1
FROM dbo.RefrigerantPricing AS f
WHERE (Type = dbo.RefrigerantPricing.Typ e) AND (Cost <= dbo.RefrigerantPricing.Cos t)) <= 3)
ORDER BY Type
I am using the following to get the best 3, but how would I then get the average per type?
SELECT TOP (100) PERCENT Type, Supplier, Cost, ID
FROM dbo.RefrigerantPricing
WHERE ((SELECT COUNT(*) AS Expr1
FROM dbo.RefrigerantPricing AS f
WHERE (Type = dbo.RefrigerantPricing.Typ
ORDER BY Type
this should do, first step:
and as you want only the top 3 per type:
from there, I think. you can do it yourself?
https://www.experts-exchange.com/Database/Miscellaneous/A_3203-DISTINCT-vs-GROUP-BY-and-why-does-it-not-work-for-my-query.html
SELECT Type, Supplier, Cost, ID, row_number() over (partition by Type order by cost asc) rn
FROM dbo.RefrigerantPricing
and as you want only the top 3 per type:
select * from (
SELECT Type, Supplier, Cost, ID, row_number() over (partition by Type order by cost asc) rn
FROM dbo.RefrigerantPricing
) sq
where sq.rn <=3
from there, I think. you can do it yourself?
https://www.experts-exchange.com/Database/Miscellaneous/A_3203-DISTINCT-vs-GROUP-BY-and-why-does-it-not-work-for-my-query.html
ASKER
Thanks both for your rapid response. I think you are giving me nore credit than I deserve, unsure how to fully compile to get the results.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thanks so much, perfect.
From(
SELECT TOP (100) [PERCENT Type], Supplier, Cost, ID
FROM dbo.RefrigerantPricing
WHERE ((SELECT COUNT(*) AS Expr1
FROM dbo.RefrigerantPricing AS f
WHERE (Type = dbo.RefrigerantPricing.Typ
Group by X.[PERCENT Type]