SQL查询-格式化同一表中的数据

时间:2019-04-15 10:52:58

标签: sql sql-server pivot-table

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

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

基本上,动作1和动作2定义了限制,我需要知道在执行动作1和动作2后每个ID在多少个运行位置。

1 个答案:

答案 0 :(得分: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;