1

想象一下,我有一张取消订阅某项内容的客户表:

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

等等等等

以及另一个每月订阅客户的表格及其订阅

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

等等等等

我需要计算第一个表中 3 个月内未出现在第二个表中的所有行。例如,如果客户 987 在 201302(二月)和 201305(五月)之间没有出现在第二个表中,我需要计算他

我目前有以下内容:

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 之间进行内部连接,但最终总数超过了相应月份表一中的记录量。

4

2 回答 2

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 回答
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 添加到选择中以在结果中查看它。

于 2013-02-22T17:23:46.783 回答