SQL用于计算给定日期之间的被动订阅者

时间:2012-02-11 09:32:43

标签: sql count inner-join

我已经整夜工作完成了我正在研究的项目的统计数据。此统计部分的一部分是向管理员显示哪些订阅者在给定日期之间未续订订阅。

TABLES

- members -
id (int)
hasSubscription (enum 1,0)

- subscriptions -
id (int)
member_id (int)
endDate (date)
active (enum 1,0)

示例

SELECT COUNT(*) FROM members as m 
INNER JOIN subscriptions as s ON s.member_id = m.id
WHERE
s.endDate BETWEEN '2011-01-01' AND '2011-02-01'
s.active = 0
m.hasSubscription = 1

通常情况下,我可以计算在两个约会日期之间完成订阅和订阅的会员。

我所追求的是拥有订阅数量的成员,这些成员在给定的2个日期之间结束但没有更多有效订阅。

此时我不能再思考了。如果你能帮助我,我会很高兴的。

2 个答案:

答案 0 :(得分:1)

听起来你需要这样的东西:

SELECT  COUNT(*) 
FROM    members as m 
        INNER JOIN subscriptions AS s 
            ON s.member_id = m.id
WHERE   s.endDate BETWEEN '2011-01-01' AND '2011-02-01'
AND     s.active = 0
AND     m.hasSubscription = 1
AND     NOT EXISTS
        (   SELECT  1
            FROM    Subscriptions a
            WHERE   a.MemberID = m.ID
            AND     a.Active = 1
        )

答案 1 :(得分:0)

了解执行计划如何随这两个查询而变化将会很有趣。根据过去的经验,此版本与LEFT JOIN应该更有效 -

SELECT  COUNT(*) 
FROM    members as m 
INNER JOIN subscriptions AS s 
    ON s.member_id = m.id
    AND s.endDate BETWEEN '2011-01-01' AND '2011-02-01'
    AND s.active = 0
LEFT JOIN subscriptions a
    ON a.member_id = m.id
    AND s.endDate < a.endDate
    AND a.active = 1
WHERE m.hasSubscription = 1
AND a.member_id IS NULL