更新列GROUP BY SUM

时间:2014-10-29 22:03:43

标签: sql group-by sql-server-2012 sql-update sum

我有两张桌子

CREATE TABLE TableB (Grp_ID int, PAmt int, Split float)
CREATE TABLE TableC (Grp_ID int,Code_ID int)

我想计算拆分的百分比,这样如果我在表C中有一个code_ID值,它链接到tableB中的两个grp_id,它应该被拆分。 (PAMT / SUM(PAMT)) 换句话说,

Case1  
INSERT INTO TableB (Grp_ID, PAmt)
VALUES (1234,2280) , (1235,3420);

INSERT INTO TableC (Grp_ID,Code_ID)
VALUES (1234,102) , (1235,102)

Expected Result:
TableB
grp_ID  PAmt Split
1234    2280  0.4  (2280 / (2280+3420))
1235    3420  0.6  (3420 / (2280+3420))

Case2 

INSERT INTO TableB (Grp_ID, PAmt)
VALUES (5174,1400) , (5175,2400);

INSERT INTO TableC (Grp_ID,Code_ID)
VALUES (5174,009) , (5175,010)

Expected Result:
TableB
grp_ID  PAmt Split
5174    1400  1 (because there is only one code for 5174) (1400/1400)
5175    2400  1 (because there is only one code for 5175) (2400/2400)



Case3 

INSERT INTO TableB (Grp_ID, PAmt)
VALUES (1111,480) , (1112,480) ,(1113,480) , (1114,960) ;

INSERT INTO TableC (Grp_ID,Code_ID)
VALUES (1111,777) , (1112,777) , (1113,778),(1114,778)

Expected Result:
TableB
grp_ID  PAmt Split
1111    480  0.50   ( 480 / (480+480))
1112    480  0.50   ( 480 / (480+480))
1113    480  0.33   ( 480 / (480+960))
1114    960  0.67   ( 960 / (480+960))

1 个答案:

答案 0 :(得分:0)

使用标准SQL99:

SELECT
    TableB.Grp_ID, TableB.PAmt,
    1.0 * TableB.PAmt / x.Sum_PAmt AS Split
FROM TableB
INNER JOIN TableC ON TableC.Grp_ID = TableB.Grp_ID
INNER JOIN (
  SELECT TableC.Code_ID, SUM(TableB.PAmt) AS Sum_PAmt
  FROM TableB
  INNER JOIN TableC ON TableC.Grp_ID = TableB.Grp_ID
  GROUP BY TableC.Code_ID
) AS x ON x.Code_ID = TableC.Code_ID

使用SQL2003中的窗口函数,由某些数据库支持:

SELECT
    TableB.Grp_ID, TableB.PAmt,
    1.0 * TableB.PAmt / SUM(TableB.PAmt) OVER (PARTITION BY TableC.Code_ID) AS Split
FROM TableB
INNER JOIN TableC ON TableC.Grp_ID = TableB.Grp_ID