我有一张像这样的表:
id | Customer | date ----------------------------------------- 1 | Customer2 | 2013-08-01 00:00:00 ----------------------------------------- 2 | Customer1 | 2013-07-15 00:00:00 ----------------------------------------- 3 | Customer1 | 2013-07-01 00:00:00 ----------------------------------------- . | ... | ... ----------------------------------------- n | CustomerN | 2012-03-01 00:00:00
我想计算每个月“获得”的客户,每个月“失去”的客户以及每个月的净收益,即使是在单独的表/视图中完成。
我该怎么做?
修改
好的,让我展示一下到目前为止我做过的事情。
要选择任何月份的已获客户,我尝试从预订表中选择以下不存在的客户:
select Customer
from Bookings
where not exists
(select Customer
from Bookings
where
(Bookings.date BETWEEN
DATE_FORMAT(DATE_SUB(Bookings.date, INTERVAL 1 MONTH), '%Y-%m-01 00:00:00')
AND DATE_FORMAT(Bookings.date, '%Y-%m-01 00:00:00'
)
) AND Bookings.date >= STR_TO_DATE('2010-11-01 00:00:00', '%Y-%m-%d 00:00:00'))
这可能会让那些存在于“选定”月份但不会存在于前一个月的客户。 “2010-11-01”是预订开始日期+ 1个月。
要选择任何月份的失去客户,我尝试从预订表中选择以下不存在的客户:
select Customer
from Booking
where not exists
(select Customer
from Bookings
where
(Bookings.date BETWEEN
DATE_FORMAT(Bookings.date, '%Y-%m-01 00:00:00')
AND Bookings.date
)
AND Bookings.date >= STR_TO_DATE('2010-11-01 00:00:00', '%Y-%m-%d 00:00:00'
)
)
这可以说是上个月存在的客户,而不是“选定”的客户。
对于“丢失”SQL查询,我得到了空结果!对于“增益”,我得到了数千行,但不确定这是否准确。
答案 0 :(得分:0)
您可以使用COUNT DISTINCT来计算您的客户,并使用WHERE YEAR(日期)= [年]和月(日期)= [月]来获得月份。
2013年9月的客户总数:
SELECT COUNT(DISTINCT Customer) AS MonthTotalCustomers FROM table
WHERE YEAR(date) = 2013 AND MONTH(date) = 9
客户于2013年9月获得了收益:
SELECT COUNT(DISTINCT Customer) AS MonthGainedCustomers FROM table
WHERE YEAR(date) = 2013 AND MONTH(date) = 9
AND Customer NOT IN
(SELECT Customer FROM table
WHERE date < '2013-09-01')
找出失去的客户更加困难。我需要知道你认为它们被丢失的标准。如果你只是意味着他们在2013年8月左右,但他们在2013年9月不在身边:
SELECT COUNT(DISTINCT Customer) AS MonthLostCustomers FROM table
WHERE YEAR(date) = 2013 AND MONTH(date) = 8
AND Customer NOT IN
(SELECT Customer FROM table
WHERE YEAR(date) = 2013 AND MONTH(date) = 9)
我希望通过这些例子,您可以推断出您正在寻找的内容。