【问题标题】:SQL: Perform calculation across rows, creating a new row for the resultSQL:跨行执行计算,为结果创建一个新行
【发布时间】:2021-05-26 12:11:09
【问题描述】:

我用 GROUP BY 对不同的值进行了总结和计数,得到了以下结果:

DATE | Parameter | Count 
2000 | Desired   | 10
2000 | Reality   | 9
2001 | Desired   | 17
2001 | Reality   | 17
etc.

现在我想计算每年的百分比现实/期望,并将结果存储在新行中,参数名为百分比。 就像:

DATE | Parameter | Count 
2000 | Desired   | 10
2000 | Reality   | 9
2000 | Percentage| 90
2001 | Desired   | 17
2001 | Reality   | 17
2001 | Percentage| 100
etc.

我已经考虑过联接之外的一些组合、用于计算百分比的窗口函数并使用 CTE 和 UNION ALL 创建新行,但我陷入困境并需要一些灵感。

非常感谢!

【问题讨论】:

  • 请标记您正在使用的 RDBMS。

标签: sql row common-table-expression percentage calculation


【解决方案1】:

一种方法使用条件聚合:

select date, parameter, count
from t
union all
select date, 'Percentage',
       ( sum(case when parameter = 'Reality' then count end) /
         sum(case when parameter = 'Desired' then count end)
       )
from t
group by date;

我应该注意,如果您想将行实际添加到表中,您可以insert 第二个查询的结果。

【讨论】:

    猜你喜欢
    • 2010-12-22
    • 2021-12-14
    • 2018-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多