SQL查询 - 来自同一表的格式数据

问题描述 投票:1回答:1

我有一个非常大的查询,它返回以下格式的数据:

ID           ACTION                    DATE
----------------------------------------------------------
1            RUN                       2018-02-15
1            ACTION 1                  2018-02-10
1            ACTION 2                  2018-02-01
1            RUN                       2018-02-02
1            RUN                       2018-02-03
1            RUN                       2018-02-11
1            RUN                       2018-02-13
2            RUN                       2018-02-15
2            ACTION 1                  2018-02-10
2            ACTION 2                  2018-02-05
2            RUN                       2018-02-02
2            RUN                       2018-02-03
2            RUN                       2018-02-11
2            RUN                       2018-02-13

我必须将此查询用作子查询并获取如下数据:

ID           RUNS_AFTER_ACTION_1                RUNS_AFTER_ACTION_2
----------------------------------------------------------------------
1            3                                  5
2            3                                  3

基本上,Action 1和Action 2定义了我需要知道在执行Action 1和Action 2之后每个ID的运行次数的限制。

sql sql-server pivot-table
1个回答
4
投票

您可以使用窗口函数和条件聚合:

select id,
       sum(case when action = 'RUN' and date > action1_date then 1 else 0 end) as RUNS_AFTER_ACTION_1,
       sum(case when action = 'RUN' and date > action2_date then 1 else 0 end) as RUNS_AFTER_ACTION_2
from (select t.*,
             max(case when action = 'ACTION 1' then date end) over (partition by id) as action1_date,
             max(case when action = 'ACTION 2' then date end) over (partition by id) as action2_date
      from t
     ) t
group by id;
© www.soinside.com 2019 - 2024. All rights reserved.