如何从表中生成以下统计信息?

时间:2021-07-07 02:08:24

标签: mysql sql

我有一个名为 incident_summary 的表,其结构和数据如下:

month,system_id,s_count

202104,1,50

202104,2,6

202105,1,14

202105,2,4

202106,1,1

202106,2,1

我想生成以下统计信息:

s_count_on_202106,s_count_before_202106

2,74

哪里

s_count_on_202106 是 202106 上 s_count 值的总和

s_count_before_202106 是 202106 之前的 s_count 值的总和

我尝试了以下 SQL:

select  
  sum(case when month<202106 then s_count else 0 end)
  sum(case when month=202106 then s_count else 0 end)
from incident_summary
group by month 

然而,它不起作用,你能帮我解决问题吗?

2 个答案:

答案 0 :(得分:1)

尝试以下查询。 可能对你有帮助。

SELECT
    t1.s_count_on_202106,
    t2.s_count_before_202106
FROM
(
    SELECT
        sum(s_count) AS s_count_on_202106
    FROM
        incident_summary
    WHERE
        month = 202106
) AS t1,
(
    SELECT
        sum(s_count) AS s_count_before_202106
    FROM
        incident_summary
    WHERE
        month < 202106
) AS t2

答案 1 :(得分:0)

对结果集再次求和。

SELECT SUM(s_count_before_202106)s_count_before_202106,  SUM(s_count_on_202106)s_count_on_202106
FROM
(
    select  
      sum(case when month<202106 then s_count else 0 end)s_count_before_202106 ,
      sum(case when month=202106 then s_count else 0 end)s_count_on_202106
    from incident_summary
    group by month
)T;