4

可以说,我有产品和分数表。

Product
-------
id
name

Score
-----
id
ProductId
ScoreValue

我想获得 AVERAGE 得分最高的前 10 款产品,如何获得平均值并在一个 select 语句中选择前 10 款产品?

这是我的,它选择了意外的行

SELECT TOP 10 Product.ProductName Score.Score 
FROM Product, Score 
WHERE Product.ID  IN (select top 100  productid  
                       from score 
                       group by productid 
                       order by sum(score) desc) 
order by Score.Score desc
4

3 回答 3

4

这可能会做到

SELECT TOP 10 p.ProductName, avg( s.Score ) as avg_score
FROM Product p
    inner join Score s on s.product_id = p.product_id
group by p.ProductName, p.product_id
order by avg_score desc
于 2013-04-25T12:10:17.440 回答
2

试试这个,

WITH records
AS
(
    SELECT  a.ID, a.Name, AVG(b.ScoreValue) avg_score,
            DENSE_RANK() OVER (ORDER BY AVG(b.ScoreValue) DESC) rn
    FROM    Product a
            INNER JOIN Score b
                ON a.ID = b.ProductID
    GROUP   BY a.ID, a.Name
)
SELECT  ID, Name, Avg_Score
FROM    records
WHERE   rn <= 10
ORDER   BY avg_score DESC

我不使用的原因TOP是因为它不会处理具有最高平均值的重复记录。但你可以TOP WITH TIES改用。

于 2013-04-25T12:06:09.147 回答
2

请试试:

declare @Product as table (id int, name nvarchar(20))
declare @Score as table (id int, ProductID int, ScoreValue decimal(23, 5))

insert into @Product values (1, 'a'), (2, 'b'), (3, 'c')

insert into @Score values (1, 1, 25), (2, 1, 30), (3, 2, 40), (4, 2, 45), (5, 3, 3)

select 
    distinct top 2 name, 
    ProductID, 
    AVG(ScoreValue) over (partition by name) 
from @Product a inner join @Score b on a.id=b.ProductID
order by 3 desc

相应地更改您的表名和行数。

于 2013-04-25T12:09:33.737 回答