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 か月の範囲に存在しないかを確認することです。それは理にかなっていますか?

例: 上記の表の 201201 (1 月) のサブスクライバー ID 106 を使用します。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 に購読をやめた人の行と、彼らが購読をやめた日付があるということです。問題は、これが本物ではない可能性があることです。おそらく、サブスクリプションを変更したか、1 か月後に再サブスクリプションしただけです。表 2 は、各月のサブスクライバーでいっぱいの表です。表 1 で退会したと記載されている日付から次の 3 か月の間に表 2 に表示されているかどうかを確認して、誰が本当に退会したかを確認する必要があります。お役に立てれば。

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 に答える