通过细分分析从总价值中计算出的百分比

时间:2018-10-03 00:39:50

标签: c# sql sql-server

我有两列:nameplantplantproduct。不同的plantproduct属于同一个nameplant。我需要从属于该植物的plantproduct总数中计算每个plantproduct的百分比。

示例:

Clapla clapro cantid        %
cyala  11002      10     66.6
cyala  11003       5     33.3
cyalb  12001      20     80.0
cyalb  12002       5     20.0

我有这个子查询,但是不起作用:

SqlCommand cmddata = new SqlCommand("SELECT clapla, clapro, (SUM(cantid)/'" + GVar.diastot + "')/totsumcan FROM (SELECT clapla, SUM(sumcantid) AS totsumcan FROM (" +
                 " SELECT clapro, clapla, (SUM(cantid)/'" + GVar.diastot + "') AS sumcantid FROM datcpc WHERE fechab >= '" + GVar.xxini + "' AND fechab <= '" + GVar.xxfin + "' AND  clacen = '" + GVar.refi + "' AND tipflu = 'C' GROUP BY Clapro, clapla) AS inner_query) FROM datcpc GROUP BY clapla ) GROUP BY clapla,clapro ; ", adtabase); 

1 个答案:

答案 0 :(得分:0)

我假设解决方案示例中的@t表已经是从DATCPC表提取数据的预聚合结果。我只演示如何计算百分比。

-- SAMPLE DATA PREPARATION
declare @t as table ( 
     Clapla varchar(10)
    ,clapro varchar(10)
    ,cantid int
);

insert into @t values ('cyala','11002',10),('cyala','11003',5),('cyalb','12001',20),('cyalb','12002',5);

还有我为您解决的问题。

-- SOLUTION EXAMPLE
select Clapla,clapro,cantid,cast(cantid*100.0/SUM(cantid) over(partition by Clapla) as numeric(4,1)) pct from @t;

更新。 SQL Server 2008的解决方案。

-- SOLUTION EXAMPLE version 2008
with agg as ( 
    select Clapla,SUM(cantid) as Total 
    from @t 
    group by Clapla )
select t1.Clapla,t1.clapro,t1.cantid,cast(t1.cantid*100.0/agg.Total as numeric(4,1)) pct 
    from @t t1 join agg on t1.Clapla = agg.Clapla;