【问题标题】:How to count the number of occurrent of each user ID with conditions in SQL databaseSQL数据库中如何统计每个用户ID的出现次数
【发布时间】:2021-04-02 00:40:55
【问题描述】:

我在 MS SQL 中有一个表格,用于收集营销活动中每个 ID 的状态。每个月都有一列检查每个消费者 ID 是否在营销活动中(is_in_programme),如果是,则在每个月中,他们是否是我们计划的新成员(is_new_apply)。每个ID可以在程序中多次申请。

我的表包含日期时间(在每个月的最后一天报告,没有跳过的月份)、ID、每个 ID 的状态,如上所述。而且我想检查在每个时期,每个 ID 在这个程序中出现了多少次(在EXPECTED 列上)。

在我的Output 列中,当is_in_programmeis_new_apply 都是1 时,我尝试使用idis_in_programmeis_new_apply 分区的ROW_NUMBER() 函数。但我不能检查is_new_apply == 0时每个ID的出现

+------------+-------+-----------------+--------------+--------+----------+
|  datetime  |  ID   | is_in_programme | is_new_apply | Output | EXPECTED |
+------------+-------+-----------------+--------------+--------+----------+
| 31/01/2020 | 12345 |               1 |            1 |      1 |        1 |
| 29/02/2020 | 12345 |               1 |            0 |      0 |        1 |
| 31/03/2020 | 12345 |               1 |            0 |      0 |        1 |
| 30/04/2020 | 12345 |               1 |            0 |      0 |        1 |
| 31/05/2020 | 12345 |               0 |            0 |      0 |        0 |
| 30/06/2020 | 12345 |               1 |            1 |      2 |        2 |
| 31/07/2020 | 12345 |               1 |            0 |      0 |        2 |
| 31/08/2020 | 12345 |               1 |            0 |      0 |        2 |
| 31/01/2020 | 67890 |               0 |            0 |      0 |        0 |
| 29/02/2020 | 67890 |               1 |            1 |      1 |        1 |
| 31/03/2020 | 67890 |               1 |            0 |      0 |        1 |
| 30/04/2020 | 67890 |               0 |            0 |      0 |        0 |
| 31/05/2020 | 67890 |               0 |            0 |      0 |        0 |
| 30/06/2020 | 67890 |               1 |            1 |      2 |        2 |
| 31/07/2020 | 67890 |               1 |            0 |      0 |        2 |
| 31/08/2020 | 67890 |               1 |            0 |      0 |        2 |
| 30/09/2020 | 67890 |               0 |            0 |      0 |        0 |
| 31/10/2020 | 67890 |               1 |            1 |      3 |        3 |
| 30/11/2020 | 67890 |               1 |            0 |      0 |        3 |
| 31/12/2020 | 67890 |               1 |            0 |      0 |        3 |
+------------+-------+-----------------+--------------+--------+----------+

有没有办法像我的EXPECTED 列一样检查每个 ID 在每个时期的营销活动中出现了多少次?

【问题讨论】:

    标签: sql sql-server gaps-and-islands


    【解决方案1】:

    is_in_program 不是0 时,您似乎想要is_new_apply 的累积总和。那将是:

    select t.*,
           (case when is_in_program <> 0
                 then sum(is_new_apply) over (partition by id order by datetime)
                 else 0
            end) as expected
    from t;
    

    【讨论】:

      猜你喜欢
      • 2014-10-16
      • 2014-08-02
      • 2022-12-03
      • 1970-01-01
      • 2014-01-17
      • 2020-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多