简体   繁体   中英

SUM data based on another column

I am trying to get the SUM of data based on their GROUPNO .

I want to put the SUM of VALUE based on GROUPNO and put it into the VALUE of data with a SUM type within the same GROUPNO .

This is my table:

ID       NAME          Type        VALUE          GROUPNO
1      PRODUCTS       HEADER       NULL             1
2       Pencil          A           10              1
3       Ruler           A           20              1
4     TOTALPROD        SUM         NULL             1
5       FOODS         HEADER       NULL             2
6       Donut           A           40              2
7       Bread           A           40              2 
8     TOTALFOODS       SUM         NULL             2  

I want my table to be like this:

ID       NAME          Type        VALUE          GROUPNO    
1      PRODUCTS       HEADER       NULL             1
2       Pencil          A           10              1
3       Ruler           A           20              1
4     TOTALPROD        SUM          30              1
5       FOODS         HEADER       NULL             2
6       Donut           A           40              2
7       Bread           A           40              2 
8     TOTALFOODS       SUM          80              2 

You can use an inner select like this:

UPDATE t
Set Value = isnull((SELECT Sum(t1.VALUE) FROM yourTable t1 
                   WHERE t1.GroupNo = t.GroupNo AND t1.Type = 'A'), 0)
FROM yourTable t
WHERE t.Type = 'SUM'

This is full working example:

DECLARE @DataSource TABLE
(
    [ID] TINYINT IDENTITY(1,1)
   ,[NAME] VARCHAR(18)
   ,[Type] VarCHAR(8)
   ,[VALUE] INT
   ,[GROUPNO] TINYINT
);

INSERT INTO @DataSource ([NAME], [Type], [VALUE], [GROUPNO])
VALUES('PRODUCTS', 'HEADER', NULL, '1')
     ,('Pencil', 'A', '10', '1')
     ,('Ruler', 'A', '20', '1')
     ,('TOTALPROD', 'SUM', NULL, '1')
     ,('FOODS', 'HEADER', NULL, '2')
     ,('Donut', 'A', '40', '2')
     ,('Bread', 'A', '40', '2')
     ,('TOTALFOODS', 'SUM', NULL, '2');

 WITH DataSource ([GROUPNO], [Value]) AS
 (
     SELECT [GROUPNO]
           ,SUM([Value])
     FROM @DataSource
     WHERE [Type] = 'A'
     GROUP BY [GROUPNO]
 )
 UPDATE @DataSource
 SET [VALUE] = DS2.[Value]
 FROM @DataSource DS1
 INNER JOIN DataSource DS2
    ON DS1.[GROUPNO] = DS2.[GROUPNO]
    AND DS1.[Type] = 'SUM'

SELECT *
FROM @DataSource

在此处输入图片说明

Something like this:

DECLARE @GrpNum int = 1

UPDATE [Table_Name] SET VALUE = 
    (SELECT SUM(VALUE) FROM [Table_Name] WHERE GroupNo = @GrpNum AND Type = 'A')

WHERE GroupNo = @GrpNum AND Type = 'SUM'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM