# SQL - How to do percent to total for each groups of record

I have the following dataset

Fund |  FundID | Unit | Price | Mkt Value
----------------------------------------------------------
ABC        123             1         10               10
ABC        123             1         20               20
ABC         456            1         30               30
DEF          456            1         40               40
DEF          789            1         50               50
XYZ          789            1         60               60
XYZ          123            1         70               70
XYZ          456            1         80               80

I would like to manipulate to get

FundID  | Subtotal |Percent Total
-------------------------------------------------
123               100               27.78
456               150               41.67
789               110               31.55

Can it possible to write a SQL statement to do this?
###### Who is Participating?

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Commented:
Something like this:

``````;WITH    MyCTE
AS (SELECT    FundID,
SUM(Price) SubTotal
FROM      YourTable
GROUP BY  FundID
)
SELECT  c1.FundID,
c1.SubTotal,
(c1.SubTotal * 100.0) / c2.Total
FROM    MyCTE c1
CROSS JOIN (SELECT  SUM(SubTotal) Total
FROM    MyCTE
) c2
``````
Commented:
This is how I tested it:

``````DECLARE @Table TABLE
(
Fund char(3) NOT NULL,
FundID smallint NOT NULL,
Unit tinyint NOT NULL,
Price tinyint NOT NULL,
MktValue tinyint NOT NULL
)

SET NOCOUNT ON

INSERT  @Table
(Fund, FundID, Unit, Price, MktValue)
VALUES  ('ABC', 123, 1, 10, 10),
('ABC', 123, 1, 20, 20),
('ABC', 456, 1, 30, 30),
('DEF', 456, 1, 40, 40),
('DEF', 789, 1, 50, 50),
('XYZ', 789, 1, 60, 60),
('XYZ', 123, 1, 70, 70),
('XYZ', 456, 1, 80, 80);

WITH    MyCTE
AS (SELECT    FundID,
SUM(Price) SubTotal
FROM      @Table
GROUP BY  FundID
)
SELECT  c1.FundID,
c1.SubTotal,
(c1.SubTotal * 100.0) / c2.Total
FROM    MyCTE c1
CROSS JOIN (SELECT  SUM(SubTotal) Total
FROM    MyCTE
) c2
``````

Output:
FundID      SubTotal      (No column name)
123      100      27.777777777777
456      150      41.666666666666
789      110      30.555555555555

Experts Exchange Solution brought to you by