代码之家  ›  专栏  ›  技术社区  ›  The KNVB

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

  •  0
  • The KNVB  · 技术社区  · 5 年前

    我有一张桌子叫 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 是 s_count 202106年价值

    s_count_before_202106 是 s\U计数 202106年前的价值

    我尝试了以下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 回复  |  直到 5 年前
        1
  •  1
  •   selvarajmas    5 年前

    请尝试以下查询。

    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
    
        2
  •  0
  •   Amit Verma    5 年前

    在结果集中再次求和。

    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;