SUM数据基于另一列

时间:2015-04-07 10:21:25

标签: sql sql-server tsql sum

我正在尝试根据GROUPNO获取数据的总和。

我想根据SUM放置VALUE GROUPNO并将其放入同一VALUE类型的SUM数据中{1}}。

这是我的表:

GROUPNO

我希望我的桌子像这样:

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  

3 个答案:

答案 0 :(得分:3)

你可以使用这样的内部选择:

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'

答案 1 :(得分:2)

这是完整的工作示例:

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

enter image description here

答案 2 :(得分:-1)

这样的事情:

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'