You may want to use a derived table (uncorrelated subquery) to get the total of the values for a particular @DateID
. Consider the following example:
SELECT t.*, (t.ValueInDate / dt.sum_value) * 100 as perc
FROM your_table t
JOIN (
SELECT SUM(ValueInDate) sum_value, DateId
FROM your_table
WHERE DateID = @DateID
GROUP BY DateId
) dt ON (dt.DateID = t.DateID)
WHERE t.DateID = @DateID;
Test case:
CREATE TABLE your_table (
StockID int, FundID int, DateID int, ValueInDate decimal(10,2)
);
INSERT INTO your_table VALUES (1, 1, 1, 35);
INSERT INTO your_table VALUES (2, 1, 1, 75);
INSERT INTO your_table VALUES (3, 2, 1, 25);
INSERT INTO your_table VALUES (4, 2, 1, 50);
INSERT INTO your_table VALUES (5, 3, 2, 15);
INSERT INTO your_table VALUES (6, 3, 2, 25);
INSERT INTO your_table VALUES (7, 4, 2, 30);
INSERT INTO your_table VALUES (8, 4, 2, 60);
Result when @DateID = 1
:
+---------+--------+--------+-------------+-----------+
| StockID | FundID | DateID | ValueInDate | perc |
+---------+--------+--------+-------------+-----------+
| 1 | 1 | 1 | 35.00 | 18.918919 |
| 2 | 1 | 1 | 75.00 | 40.540541 |
| 3 | 2 | 1 | 25.00 | 13.513514 |
| 4 | 2 | 1 | 50.00 | 27.027027 |
+---------+--------+--------+-------------+-----------+
4 rows in set (0.00 sec)