I have two tables
CREATE TABLE TableB (Grp_ID int, PAmt int, Split float)
CREATE TABLE TableC (Grp_ID int,Code_ID int)
I want to calculate the percentage of split so that if I have one code_ID value in table C, which links to two grp_ids in tableB , It should get split up. (PAmt/SUM(PAmt)) In other words,
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))
Using standard 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
Using window functions from SQL2003, supported by some databases:
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
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.