1

何かの購読を解除した顧客のテーブルがあるとします。

DateMonthID     customerID
   201301           123
   201301           321
   201302           987
   201303           567
   201303           728

などなど

毎月のサブスクライバーである顧客とそのサブスクリプションの別のテーブル

DateMonthID     customerID     subscriptionType
   ...              ...               1
   ...              ...               3
   ...              ...               2
   ...              ...               3

などなど

2 番目のテーブルに 3 か月間表示されない最初のテーブルのすべての行をカウントする必要があります。たとえば、201302 (2 月) から 201305 (5 月) の間に 2 番目のテーブルに表示されない顧客 987 をカウントする必要があります。

私は現在、次のものを持っています:

SELECT
    COUNT(1) AS Total,
    table1.DateMonthID AS MonthID
FROM
    table1
WHERE
table1.DateMonthID <= 201212-3
AND NOT EXISTS (SELECT * FROM table2
                        WHERE (table2.DateMonthID >= table1.DateMonthID AND table2.DateMonthID <= (table1.month_key + 3))
                        AND table2.customerID = table1.customerID)
GROUP BY
table1.DateMonthID

これにより、次のような出力が得られます

Total  MonthID
1000    201301
2345    201302
4532    201303
986     201304
etc      etc

これは問題ないように思えますが、私が今やりたいことは、サブスクリプションタイプによるグループ化でもあります。これは、結合を行う必要があることを意味していると確信していますが、SQL にまったく慣れていないため、どの結合がどこにあるのかわかりません。customerIds 間の内部結合を試みましたが、対応する月のテーブル 1 のレコードの量を超える合計が得られました。

4

2 に答える 2

0

このクエリ(またはcount(*)を使用)

SELECT
  COUNT(table1.DateMonthID) AS Total,
  subscribers.subscriptionType
FROM
  table1
  INNER JOIN subscribers
     ON table1.DateMonthID = subscribers.DateMonthID
        AND table1.customerID = subscribers.customerID
WHERE
      table1.DateMonthID <= 201212-3
  AND NOT EXISTS (SELECT * FROM table2
                  WHERE (table2.DateMonthID >= table1.DateMonthID
                    AND table2.DateMonthID <= (table1.month_key + 3))
                    AND table2.customerID = table1.customerID)
GROUP BY subscribers.subscriptionType

サブスクライバーごとのレコードの総数が表示されます。

加入者と月ごとの内訳が必要な場合は、グループにDateMonthIDを追加します。

GROUP BY subscribers.subscriptionType, table1.DateMonthID

table1.DateMonthIDをselectに追加して、結果に表示することを忘れないでください。

于 2013-02-22T17:23:46.783 に答える
0

このクエリを試してください

SELECT COUNT(*) AS Total, table1.DateMonthID AS MonthID, subscribers.subscriptionType
FROM table1 JOIN subscribers ON table1.DateMonthID = subscribers.DateMonthID
                                  AND table1.customerID = subscribers.customerID
WHERE table1.DateMonthID <= 201212 - 3
AND NOT EXISTS (SELECT *
                FROM table2
                WHERE (table2.DateMonthID >= table1.DateMonthID 
                  AND table2.DateMonthID <= (table1.month_key + 3))
                  AND table2.customerID = table1.customerID)
GROUP BY table1.DateMonthID, subscribers.subscriptionType
于 2013-02-22T22:53:34.033 に答える