查询未出现在另一个表的日期范围中的行数

时间:2013-02-22 17:11:12

标签: sql

想象一下,我有一张客户表,这些客户已取消订阅:

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

等等

另一个客户表,每个月都是订阅者及其订阅

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

等等

我需要计算第一个表中未出现在第二个表中3个月的所有行。例如,如果他在201302(feb)和201305(可能)之间未出现在第二个表格中,我需要计算客户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中相应月份的记录数量。

2 个答案:

答案 0 :(得分: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中以在结果上查看它。

答案 1 :(得分: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