我正在制作一个查询,让我了解客户的习惯,例如 - 平均花费,预订数量等。
我当前的查询看起来像
SELECT email,
Avg(amount_paid) AS avg_paid,
Count(*) AS no_times_booked
FROM bookings
GROUP BY email
这为我提供了电子邮件,平均支出和预订次数
我的表看起来像
email | amount_paid | booking_date
email@email.com | 50.00 | 2010-01-13
email@email.com | 50.00 | 2010-01-13
email@email.com | 50.00 | 2010-01-13
如何调整查询以获得每月平均预订次数?
所以我的结果如下所示,最终我的用户数是每个用户一个平均数 - 如果他们只在下个月预订一次,他们的平均数就会下降。
或者换句话说,我试图标记普通客户 - 每月或更高的预订将是常规的。
email | avg_spend | number_bookings | avg_bookings_per_month
email@email.com | 50.00 | 3 | 3
答案 0 :(得分:0)
您拥有大部分内容,但为了获得每月的平均预订量,您需要嵌套查询。最内部的查询将基于电子邮件帐户的分组和预订的月份/年份(以免混淆2014年1月和2015年1月的数字)。
SELECT
PreAgg.email,
sum( PreAgg.overallPaid ) as TotalPaid,
sum( PreAgg.timesBooked ) as TimesBooked,
sum( PreAgg.overallPaid ) / sum( PreAgg.timesBooked ) as OverallAvgPd,
Avg( PreAgg.ThisMthYrAvgPd ) as AvgPerMthYr
FROM
( SELECT
email,
year( booking_date ) as bkYear,
month( booking_date ) as bkMth
sum( amount_paid ) as overallPaid,
count( * ) as timesBooked,
avg( amount_paid ) as ThisMthYrAvgPd
from
bookings
group by
email
year( booking_date ),
month( booking_date ) ) PreAgg
GROUP BY
PreAgg.email
然而,这将获得大部分,它不会得到它,因为我们没有查询所代表的时间段的上下文。每月/每年的平均值就是这个数字。但是如果你知道你要查询的时间段(例如:2014年全年),那么你需要计算每月平均值12来获得更准确的每月费率。有人可以在一个月内旅行3次,然后在6个月内旅行,然后再旅行2次。总共5次,但只有2个月的活动。因此,您需要如何量化“常规”访客/访客身份。如果在12个月中预订的2个月与12个月中的5个预订总数相比给出了完全不同的分数答案。
答案 1 :(得分:0)
感谢您的帮助,继续这个
//如果在过去12个月内预订的次数相等或高于他们预订的预订月份的唯一数量,则他们是普通的预订者。
SELECT email,
Avg(amount_paid) AS avg_paid,
Count(*) AS no_times_booked,
Count(DISTINCT( Month(added) )) AS unique_months
FROM bookings
WHERE added >= Now() - INTERVAL 1 year
GROUP BY email
答案 2 :(得分:0)
使用您的查询进行测试
SELECT
YEAR(booking_date) AS YEAR,
CASE
WHEN MONTH(booking_date) = 1
THEN SUM(amount_paid)/31
ELSE 0 END JAN,
CASE
WHEN MONTH(booking_date) = 2
THEN SUM(amount_paid)/28
ELSE 0 END FEB,
CASE
WHEN MONTH(booking_date) = 3
THEN SUM(amount_paid)/31
ELSE 0 END MARCH,
CASE
WHEN MONTH(booking_date) = 4
THEN SUM(amount_paid)/30
ELSE 0 END APRL,
CASE
WHEN MONTH(booking_date) = 5
THEN SUM(amount_paid)/31
ELSE 0 END MAY,
CASE
WHEN MONTH(booking_date) = 6
THEN SUM(amount_paid)/30
ELSE 0 END JUNE,
CASE
WHEN MONTH(booking_date) = 7
THEN SUM(amount_paid)/31
ELSE 0 END JULY,
CASE
WHEN MONTH(booking_date) = 8
THEN SUM(amount_paid)/31
ELSE 0 END AUG,
CASE
WHEN MONTH(booking_date) = 9
THEN SUM(amount_paid)/30
ELSE 0 END SEP,
CASE
WHEN MONTH(booking_date) = 10
THEN SUM(amount_paid)/31
ELSE 0 END OCTOBER,
CASE
WHEN MONTH(booking_date) = 11
THEN SUM(amount_paid)/30
ELSE 0 END NOV,
CASE
WHEN MONTH(booking_date) = 12
THEN SUM(amount_paid)/31
ELSE 0 END DECE
FROM bookings
WHERE booking_date >= NOW() - INTERVAL 4 YEAR
GROUP BY 1;