Question: I created new column in table and wrote an inner join function which fills that column with values. But now i figured it out that i need that value added for each repeated `NUMBER` in table `CART`.

```
ALTER TABLE [HEADERS] ADD [SUM] [DECIMAL]
GO
UPDATE [HEADERS]
SET [HEADERS].[SUM] = [CART].[AMOUNT]*[CART].[PRICE]
FROM [HEADERS]
INNER JOIN [CART]
ON [HEADERS].[NUMBER] = [CART].[NUMBER]
GO

```

Column `NUMBER` is unique in `HEADERS` but is not unique and repeated in `CART`.

So what i need is to count `[CART].[AMOUNT]*[CART].[PRICE]` for each identical `NUMBER` in `CART`, summary this, and then fill in this value into suitable verse of table `HEADERS`- where `[HEADERS].[NUMBER] = [CART].[NUMBER]`.

I'm not rly good at databases, but i know there is no foreach loop and i need help with that task.
How can i achieve my goal?

Answer: 
Use aggregation before the `JOIN`:

```
UPDATE h
    SET h.[SUM] = c.total
    FROM HEADERS h JOIN
         (SELECT c.NUMBER, SUM(C.AMOUNT * C.PRICE) as total
          FROM CART c
          GROUP BY c.NUMBER
         ) c
        ON c.NUMBER = h.NUMBER;

```
You probably need to add the TableName C to fix the query-error and make it work:

```
UPDATE h
    SET h.[SUM] = c.[CART].[AMOUNT]*c.[CART].[PRICE]
    FROM HEADERS h JOIN
         (SELECT c.NUMBER, SUM(C.AMOUNT * C.PRICE) as total
          FROM CART c
          GROUP BY c.NUMBER
         ) c
        ON c.NUMBER = h.NUMBER;

```

Alternatively this might fix the problem: 

```
UPDATE h
    SET h.[SUM] = c.total
    FROM HEADERS h JOIN
         (SELECT c.NUMBER, SUM(C.AMOUNT * C.PRICE) as total
          FROM CART c
          GROUP BY c.NUMBER
         ) c
        ON c.NUMBER = h.NUMBER;

```