SUM第一个表在第二个CATEGORY表上

时间:2015-01-08 17:53:46

标签: sql sql-server tsql sum

我有一张桌子ProdByCat

CatID      ProductID 
---------------------------
Food        Beans
Food        Corn
Food        Peas
Drink       Juice
Drink       Wine

另一张表购买

Region        ProductID   Cost
-----------------------------
North         Beans       5
South         Beans       5
West          Beans       5
North         Corn        5
North         Peas        5 
West          Wine        10
West          Juice       10 

我想要的是拥有一张返回的表

Region     CatID   TotalCost
-----------------------------
North      Food    15
South      Food    5
West       Food    5
West       Drink   20

我确信我过度复杂了。这是我旅行的方向:

select P.Region, Y.CatID, SUM(P.Cost) As 'TotalCost'
from Purchases As P, 
(   select distinct(A.CatID), 
    Includes=( stuff ( 
         select ''''+ ProductID + ''','  
         from ProdByCat B
         where B.CatID = A.CatID
         order by ProductID
         for xml path ('')
         ),1,1,'')
    from ProdByCat A
) Y
where ProductID in (Y.Includes)
group by P.Region, Y.CatID

它的fubar' d。从语法上讲,它可以工作但返回一个空集。

我的想法是,如果我使用xml路径功能,我可以创建一个包含列表,如果ProductID存在,将允许我创建一个总和。

4 个答案:

答案 0 :(得分:3)

你是对的。你太复杂了。它可以更简单:

SELECT p.Region, pbc.CatID, SUM(p.Cost) AS TotalCost
    FROM Purchases p
        INNER JOIN ProdByCat pbc
            ON p.ProductID = pbc.ProductID
    GROUP BY p.Region, pbc.CatID;

答案 1 :(得分:2)

看起来只有Group by聚合Sum聚合应该有效。试试这个。

您的预期结果中有一个错误,最后一行应为West Drink 20。区域应为West而不是North

SELECT Region,
       CatID,
       Sum(cost) TotalCost
FROM   ProdByCat A
       JOIN Purchases b
         ON a.ProductID = b.ProductID
GROUP  BY Region,
          CatID 

答案 2 :(得分:1)

要生成您描述的表,您只需要一个内连接和一个

select 
    Region = p.Region,
    CatID = c.CatID,
    TotalCost = sum(Cost)
from #ProdByCat c
inner join #Purchases p
    on c.ProductID = p.ProductID
group by p.Region, c.CatID

但是你的xml代码让你听起来像是在寻找与每个组相关联的产品的分隔列表。如果这就是你需要的,请告诉我。

答案 3 :(得分:1)

让我们创建测试数据:

DECLARE @ProdByCat TABLE
(
    CatID VARCHAR(10),
    ProductID VARCHAR(10)
)

INSERT INTO @ProdByCat
( CatID, ProductID )
VALUES
('Food'        ,'Beans'),
('Food'        ,'Corn'),
('Food'        ,'Peas'),
('Drink'       ,'Juice'),
('Drink'       ,'Wine');

DECLARE @Purchases TABLE
(
    Region VARCHAR(10),
    ProductID VARCHAR(10),
    Cost int
)

INSERT INTO @Purchases
( Region, ProductID, Cost )
VALUES
('North',         'Beans',       5),
('South',         'Beans',       5),
('West',          'Beans',       5),
('North',         'Corn',        5),
('North',         'Peas',        5),
('West',          'Wine',        10),
('West',          'Juice',       10); 

现在我们将进行加入和分组,以获得每个类别的费用:

SELECT p.Region, pc.CatId, SUM(COST) AS Cost 
FROM @Purchases p
INNER JOIN @ProdByCat pc
    ON p.ProductID = pc.ProductID
GROUP BY p.Region, pc.CatID
ORDER BY p.Region, pc.CatID DESC

输出:

Region  CatId   Cost
North   Food    15
South   Food    5
West    Food    5
West    Drink   20