SUM 第一个 table 第二个 CATEGORY table

SUM first table on second CATEGORY table

我有一个 table ProdByCat

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

另外 table 次购买

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

我想要 table returns

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

这很奇怪。从语法上讲,它有效,但 returns 是一个空集。

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

看起来 Group bySum 聚合应该可以工作。试试这个。

您的预期结果有误,最后一行应该是 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 

你是对的。你把它复杂化了。它可以简单得多:

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;

要生成您描述的 table,您只需要一个内部联接和一个分组

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 代码听起来像是您希望获得与每个组关联的产品分隔列表。如果那是你需要的,请告诉我。

让我们创建测试数据:

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