Sql server 使用3个SQL表获取平均值(价格)

Sql server 使用3个SQL表获取平均值(价格),sql-server,join,average,Sql Server,Join,Average,我想要每个类别的平均价格,其中产品通过Product_Category_映射表按类别分组 Product表有ID和Price列,我想要每个类别的所有产品的平均价格 Product Table: ID, Name, Price Category Table: ID, Name Product_Category_Mapping Table: ID, CategoryID, ProductID 有什么想法吗???您只需要了解加入sqlserver。这里我们使用innerjoin实

我想要每个类别的平均价格,其中产品通过Product_Category_映射表按类别分组

Product表有ID和Price列,我想要每个类别的所有产品的平均价格

Product Table: 
ID, 
Name, 
Price

Category Table: 
ID, 
Name

Product_Category_Mapping Table: 
ID, 
CategoryID, 
ProductID

有什么想法吗???

您只需要了解加入sqlserver。这里我们使用innerjoin实现一对一关系

declare @Category Table(ID int, Name varchar(50))
declare @Product Table(ID int, Name varchar(50), Price int)

declare @Product_Category_Mapping Table (ID int, CategoryID int, ProductID int)

insert into @Category values (1,'a'),(2,'b'),(3,'c')
insert into @Product values (1,'p1',10),(2,'p2',20),(3,'p3',30)
insert into @Product_Category_Mapping values (1,1,1),(2,1,2),(3,2,3)

select 
    c.id, avg(price)
from @Product_Category_Mapping pcm 
    inner join @Product p on p.id = pcm.ProductID
    inner join @Category c on c.id = pcm.CategoryID

group by c.id
已更新

根据您的评论,我理解并更新了以下代码。如果你有问题,告诉我

declare @Product Table(ID int, Name varchar(50), Price int)

declare @Product_Category_Mapping Table (ID int, CategoryID int, ProductID int)

insert into @Category values (1,'a'),(2,'b'),(3,'c')
insert into @Product values (1,'p1',10),(2,'p2',20),(3,'p3',30)
insert into @Product_Category_Mapping values (1,1,1),(2,1,2),(3,2,3)

select --Category.[name] as CatName, Product.[Id], Product.[Name], [Price] 
    c.id, 
    c.Name,
    p.ID,
    p.Name,
    avg(isnull(price,0)) over(partition by c.id ) as avgprice
from @Category c    
    left join @Product_Category_Mapping pcm  on c.id = pcm.CategoryID
    left join @Product p on p.id = pcm.ProductID

你为什么没有尝试过呢?是的,为什么不试着写下你自己的查询,然后问一下你的查询缺少了什么或者有什么问题。。。很好的评论Edrich,是的-我做了几次尝试,但都没有成功,如果将它们添加到问题中,会让问题变得一团糟-很好,非常好的评论,而且非常有用我尝试了这个,但无法找出为什么它没有约束力:从[Category]中选择Category.[name]作为CatName,Product.[Id],Product.[name],[Price]以map on map.CategoryId=Category.id的形式加入产品\u Category\u映射。以map.ProductID=Product.id的形式加入产品。感谢您的回复和示例!这不是约束手段。你面临的问题是什么。我查过你的密码了。为什么在查询中引入产品部分。您需要类别平均价格,那么产品是如何来的,还是只想显示所有具有平均类别价格的产品?