我有一个包含以下列的表:
StockID,FundID,DateID,ValueInDate
我想创建一个GROUP BY查询,显示每个基金总数的百分比 特定日期中的值,无参数。
我在此查询中只有@DateID
参数
有什么想法吗?
答案 0 :(得分:2)
您可能希望使用派生表(不相关的子查询)来获取特定@DateID
的值的总和。请考虑以下示例:
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;
测试用例:
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);
@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)
答案 1 :(得分:0)
这是解决方案 - 在下面的解决方案中,总金额不是针对每个基金,而是针对所有基金。我解决了一下,感谢Daniel Vassallo !!
DECLARE @DATEID int
SET @DATEID=1
SELECT t.FundID,t.ValueInDate / CAST(dt.sum_value AS FLOAT) as perc,dt.sum_value
FROM tbl_Holding_Gemel t JOIN tbl_Funds tf ON t.FundID = tf.FundID
JOIN (
SELECT SUM(ValueInDate) sum_value, FundID
FROM tbl_Holding_Gemel
WHERE DateID = @DateID
Group By FundID
) dt ON (dt.FundID = t.FundID)
WHERE t.DateID = @DateID