1

我在 table1 中有如下所示的数据:

  DateMonthID    SubscriberID    othercolumns...
     201201           106
     201201           207
     201202           309
     201203           405
     201203           297

等等等等

和 table2 像这样:

  DateMonthID    SubscriberID    Level
       ...           ...          1
       ...           ...          2
       ...           ...          1
       ...           ...          3
       ...           ...          2

等等等等

我需要做的是检查第一个表中的哪些订阅者在另一个表中未来 3 个月的范围内不存在。那有意义吗?

示例:取上表中的subscriberID 106 为日期201201(1 月)。如果 201201-201204(1-4 月)没有出现在另一个表中,我需要累积计数。

这是我到目前为止所拥有的,但它似乎返回了太多的值:

SELECT
    COUNT(1) AS Total,
    table1.month_key,
    table2.level
FROM
    dbo.table1
INNER JOIN
    dbo.table2 ON (table2.subscriber_id = table1.subscriber_id)
WHERE
    NOT EXISTS (SELECT * FROM table2
                WHERE
                (table2.month_key >= table1.month_key AND table2.month_key <= (table1.month_key + 3))
                AND table2.subscriber_id = table1.subscriber_id)
GROUP BY
table1.month_key, table2.level
ORDER BY
table2.level, table1.month_key

任何帮助将非常感激

-------------- 编辑 -------------- 只是为了让事情更清楚,因为我不确定我是否解释得很好。情况是,table1 中是停止订阅的行以及他们停止订阅的日期。问题是这可能不是真的,也许他们只是更改订阅或一个月后重新订阅。表 2 是一个包含每个月订阅者的表。我需要通过检查他们是否出现在表 2 中表示他们取消订阅的日期和接下来的 3 个月之间,找出谁真正取消了订阅。希望这可以帮助。

4

1 回答 1

2

我认为问题在于你不能在月份键中添加“3”来获得你想要的东西。试试这个:

FROM (select table1.*,
             (cast(left(month_key, 4) as int)*12+
                                cast(right(month_key, 2) as int)
                               ) as newMonthKey
      from dbo.table1
     ) table1
. . .

where not exists (select 1
                  from (select table2.*,
                               (cast(left(month_key, 4) as int)*12+
                                cast(right(month_key, 2) as int)
                               ) as newMonthKey
                        from table2
                       ) t
                  where (t.newmonthkey >= table1.newmonthkey AND t.newmonthkey <= (table1.newmonthkey + 3))
                        AND t2.subscriber_id = table1.subscriber_id
                       )

这会将月份键更改为自第 0 年以来的月份计数器。

于 2013-02-22T14:06:56.293 回答