我正在试图找出如何编写查询以查明在给定日期范围内有多少客户下订单1次,2次等。客户使用其唯一的电子邮件地址进行标识,订单应为不同的订单号。
基本上,数据会显示每次购买的大量订单ID,因为每个订单项都会获得自己的重复订单ID ...
结果应该返回1个客户,当年有4个订单。但它没有返回任何东西。任何帮助,将不胜感激。
CURRENT QUERY(我的数据库表名为amazon)
SELECT COUNT(DISTINCT amazon.`amazon-order-id`), amazon.`buyer-email`
FROM amazon
WHERE amazon.`purchase-date` >= '1/1/2014' and
amazon.`purchase-date` <= '12/31/2014'
GROUP BY amazon.`buyer-email`
HAVING COUNT(amazon.`amazon-order-id`) = 4
我正在复制并粘贴下面的一些示例数据:
*114-2021965-2390651 3/18/2014 svj8w3vj3x4y4k8@marketplace.ama4on.com
*114-2021965-2390651 3/18/2014 svj8w3vj3x4y4k8@marketplace.ama4on.com
*114-8957580-1296223 3/26/2014 svj8w3vj3x4y4k8@marketplace.ama4on.com
*114-8957580-1296223 3/26/2014 svj8w3vj3x4y4k8@marketplace.ama4on.com
*108-5564197-2113836 6/2/2014 svj8w3vj3x4y4k8@marketplace.ama4on.com
*108-5564197-2113836 6/2/2014 svj8w3vj3x4y4k8@marketplace.ama4on.com
*114-4685236-6299434 10/11/2014 svj8w3vj3x4y4k8@marketplace.ama4on.com
*114-4685236-6299434 10/11/2014 svj8w3vj3x4y4k8@marketplace.ama4on.com
答案 0 :(得分:0)
使用您的示例数据,一旦我添加了不同的查询,您的查询就会起作用 有COUNT声明。
HAVING COUNT(DISTINCT amazon.amazon-order-id) = 4
您的样本数据中的日期也给我带来了麻烦。 我必须将零添加到单个数字的数字,以便where子句正常工作。我不确定这对你很重要。
3 -> 03
6 -> 06 2-> 02
答案 1 :(得分:0)
首先,使用更标准的日期格式。
然后,如果您想要一般性答案,那么使用两个级别的聚合:
select num_orders, count(*), min(`buyer-email`), max(`buyer-email`)
from (select a.`buyer-email`,
count(distinct a.`amazon-order-id`) as num_orders
from amazon a
where a.`purchase-date` >= '2014-01-01' and
a.`purchase-date` < '2015-01-01'
group by a.`buyer-email`
) a
group by num_orders
order by num_orders;