如果可能的话,我正在努力解决这个问题:
我想通过SUM
添加行的所有值,例如:
120
6239
2810
123
这将是SUM()
,等于9292。
然后,我想运行一个查询,选择等于百分比的特定行。所以说我有79.612%,我想选择匹配这个百分比的行。
有什么想法吗?
答案 0 :(得分:0)
根据提供的信息解答您的问题,但正如我们的评论所示,我们需要更多有关百分比来源的信息。
Select * from yourTable -- The table you want to match the percentage table
where SomePercentage = select (sum(value) /
(select sum(value) from yourTable2)) * 100 -- Total value used as upper bracket of percentage
from yourTable2 where someValue like '123' -- Whatever you want to base the percentage off
编辑以匹配传入百分比的更新要求,我们得到最接近的值?到图。
Select top 1 * from yourTable where
value <= (Select (Sum(somevalues) * @In_Percentage)/100 from yourTable2)
order by value desc
答案 1 :(得分:0)
请使用以下代码。它与SQL Server 2012一起正常工作。
DECLARE @Table TABLE (Value int)
INSERT INTO @Table
(Value)
VALUES
(120),(6239),(2810),(123)
Select t.Value FROM @Table t
GROUP BY t.[Value]
HAVING (100*t.value)/(Select sum(t.Value) FROM @Table t) >79.612
答案 2 :(得分:0)
其他解决方案的替代方案:
DECLARE @VarTable TABLE (Value int);
INSERT INTO @VarTable (Value) VALUES (120),(6239),(2810),(123);
SELECT Value
FROM (
select t.Value, round(100*cast(t.value as float)/s.totalvalue, 3) as perc
from @VarTable t
join (Select sum(Value) as totalvalue FROM @VarTable) s on (1=1)
) Q2
where perc between 60.0 and 80.0;
67.144是这4个值的最高百分比:
select top 1 t.Value, s.totalvalue, round(100*cast(t.value as float)/s.totalvalue,3) as perc
from @VarTable t
join (Select sum(Value) as totalvalue FROM @VarTable) s on (1=1)
order by perc desc;