我有一个订阅表,可以按日期跟踪会员续订。续订是针对日历年的,但会员最早可以在10月1日续订,在这种情况下,他们将在下一年的12月31日之前更新。因此可以在1月续订,然后在同年10月再次更新。我按月报告了会员总数,我希望避免将其计为2个会员资格。
由于上述续订选项,每条记录都有一个唯一的prodID
,但可以有一个memberID
的记录。 payDate
是交易日期
我的陈述是:
$sql = "SELECT
EXTRACT(MONTH FROM payDate) as month,
EXTRACT(YEAR FROM payDate) as year,
count(*)
FROM
memberDues
WHERE payDate >= $lastYear-10-01
GROUP BY
month,
year
ORDER BY
year ASC,
month ASC";
我得到这样的输出(未格式化):
Member dues paid by month
October 46
November 30
December 99
January 42
February 8
March 9
April 4
May 1
June 3
Member Total: 242
如何修改select语句以避免在报告期内重复续订?
答案 0 :(得分:0)
您需要按memberID进行分组才能让一个成员续订不被重复。
SELECT year, month, count(memberID) FROM (
SELECT memberID,
EXTRACT(MONTH FROM payDate) as month,
EXTRACT(YEAR FROM payDate) as year,
count(*)
FROM
memberDues
WHERE payDate >= $lastYear-10-01
GROUP BY
memberID,
month,
year
ORDER BY
year ASC,
month ASC";
)TMP GROUP BY year, month
答案 1 :(得分:0)
为每个月计算不同的memberID应该完成这项工作:
SELECT
EXTRACT(MONTH FROM payDate) as month,
EXTRACT(YEAR FROM payDate) as year,
count(DISTINCT memberID)
FROM
memberDues
WHERE payDate >= $lastYear-10-01
GROUP BY
month,
year
ORDER BY
year ASC,
month ASC