我正在使用SQL Server 2012,并且正在尝试使用PARTITION计算目标值的百分比,但我不断收到汇总错误。百分比需要是数据集中的新行,并附加到每个组的末尾
答案 0 :(得分:1)
您可以做自己想做的事,尽管我对此很有用表示怀疑:
select group, item, jan, feb
from ((select group, item, jan * 1.0 as jan, feb * 1.0 as feb
from t
) union all
(select group, 'Percent',
sum(case when item = 'Target' then jan end) * 1.0 / sum(case when item = 'Target' then jan end),
sum(case when item = 'Target' then feb end) * 1.0 / sum(case when item = 'Target' then feb end)
from t
group by group
)
) g
order by group, charindex(item, 'Target,Actual,Percent');
group
是保留字,因此对于列而言确实是一个不好的名字。我没有费心去逃避这个名字,因为我认为那只是对查询逻辑的干扰。
答案 1 :(得分:0)
您可以尝试以下一种方法:
select field1,
perc=field1/sum(field1) over( order by field1 rows between unbounded
preceding and unbounded following)
from Table1