查询多个连接

时间:2014-04-12 20:44:54

标签: sql join sql-server-2008-r2

所以我有这个数据库:http://i.stack.imgur.com/pQD2Z.jpg

每张牌都有他的身份证,我用作PK和FK' s。我需要的是让按州获得更多销售额的产品系列,如下所示:http://i.stack.imgur.com/PrEgl.png

我做这样的事情:

select 
    Sale_Details.state_id, 
    Producto_Family.family_id, 
    familia_producto.des_familia, 
    SUM(Sale_Details.amount) as Amount

然后我从Sale_Details一直到Product_Family开始进行分组和关节,但我无法做到正确,因为我得到了一些{{1在不同的国家两次。

我应该每个州只有一个Product_Family,那个家庭有更多销售额的那个,对吗?

顺便说一下,我使用的是SQL Server 2008 R2。

2 个答案:

答案 0 :(得分:2)

尝试这样的事情:

SELECT  state, 
        PfamilyID,
        PFamilyName,
        Sales

FROM

    (   SELECT state.id as State,
        product_family.id as PfamilyID,
        product_family.name PFamilyName,
        SUM(saledetails.amount) Sales,
        row_number() over (partition by state.id order by SUM(saledetails.amount) desc) rownum

        FROM saledetails
        INNER JOIN sales ON saledetails.sales_id = sales.id
        INNER JOIN client ON sales.client_id=client.id
        INNER JOIN city ON client.city_id=city.id
        INNER JOIN state ON city.state_id=state.id
        INNER JOIN product ON saledetails.product_id=product.id
        INNER JOIN product_family ON product.product_family=product_family.id


        GROUP BY state.id,
        product_family.id,
        product_family.name ) X

WHERE rownum=1

GROUP BY    state,
            PfamilyID,
            PFamilyName,
            Sales

答案 1 :(得分:0)

这很可能是基于逐个国家的。您可以通过使用临时表,子查询甚至CTE(这是实际的CTE)来进一步巩固这一点:

select
    State.Name
    ,City.Name
    ,Client.Name
    ,Product_Family.Name
    ,sum(Sales.Amount)
from
    State
inner join  
    City
on
    State.id = City.stateid
inner join
    Client
on
    City.id = Cient.CityId
inner join
    Sales
on
    Client.Id = Sales.ClientId
inner join
    Sale_Details    
on 
    Sales.Id = sales_Details.Sales_Id
inner join
    Product
on
    Sales_Details.Product_Id = Product.Id
inner join  
    Product_Family  
        on Product.Product_Family_id = Product_Family.Id

group by
    State.Name
    ,City.Name
    ,Client.Name
    ,Product_Family.Name
order by 
    State.Name
    ,City.Name
    ,Client.Name
    ,Product_Family.Name