首页 文章

sql查询累计值计算

提问于
浏览
3

我在为以下要求生成正确的方法/查询时面临一些设计和逻辑问题 .

我的主要表是

从[table]中选择*,其中ID ='XYZ'

enter image description here

现在我已经计算了累积的风险权重,因为我需要写一个逻辑

conditions:

同一年的每个月

if(Jan) - >同年1月份RiskCategory权重的总和

if(Feb) - >同年1月和2月的RiskCategory权重之和

if(March) - > RiskCategory权重的总和从同一年的1月到3月

if(April) - >同一年1月到4月的RiskCategory权重之和

.

.

.

if(Dec) - > RiskCategory权重的总和,从同一年的1月到12月

**如果任何月份存在多个RiskCategories

情况1.如果值相同则只取一个值 .

情况2:如果不相同则取其中的最大值 .

例如,如果我们想要计算2016年11月的风险权重,那么我们应该只考虑以下行

enter image description here

**由于我没有2016年1月至9月的数据,我只考虑了11月份的10月和11月数据计算

现在的结果应该是

心血管病例为0.649(病例1)

肺部1.037(病例2)

糖尿病2型为0.666

精神病学0.798

肾脏1.896

0.536常数= 5.582

最后的结果表应该是

enter image description here

请检查sqlfiddle

http://sqlfiddle.com/#!6/8448e/6 [已更新]

http://sqlfiddle.com/#!6/d05fe/1

4 回答

  • 3

    如果我做对了你真的想要这个:

    SELECT
        ID,
        Year,
        Month,
        RiskWeight = SUM(MaxRiskweight) + 0.536
    FROM (
        SELECT
            t1.ID,
            t1.Year,
            t1.Month,
            t2.RiskCategory,
            MaxRiskweight = MAX(t2.Riskwight)
        FROM
            inputTable AS t1
            JOIN inputTable AS t2
            ON t1.ID = t2.ID AND
               t1.Year = t2.Year AND
               t2.Month <= t1.Month
        GROUP BY
            t1.ID,
            t1.Year,
            t1.Month,
            t2.RiskCategory
        ) AS MaxRiskWeights
    --WHERE
    --  ID = 'XYZ'
    GROUP BY
        ID,
        Year,
        Month
    

    我对 WHERE 子句进行了评论,因为我想你要为表中的每个 ID 计算它 . 常量 0.536 被添加到 RiskWeight 的每个汇总行,正如您在示例中给出的那样 .

  • 1

    您可以使用窗口功能 . 我相信你基本上想要:

    select t.*,
           sum(riskweight) over (partition by id, year, riskcategory
                                 order by month
                                ) as accum_riskweight
    from t;
    

    这不太有效,因为您有月份名称 - 这些将按字母顺序排序 . SQL Server非常适合转换日期,所以这应该工作:

    select t.*,
           sum(riskweight) over (partition by year, riskcategory
                                 order by convert(date, month + ' 01 2000')
                                ) as accum_riskweight
    from t;
    
  • 3
    select distinct id, year,month,SUM(riskweight) group by  ID,year,month
    
  • 1

    您可以使用Sum与窗口函数如下:

    Select *, RiskWeight = Sum(Riskwight) over (Partition by Id, [Year] order by [Month]) 
     from (
     Select Id, [Year], [Month], RiskWight = Sum(riskWight) from inputtable
        Group by Id, [Year], [Month]
        ) a
    order by [year], [Month]
    

    但是这里[月]顺序依次按字母顺序排列,最好在这个地方有月号

相关问题