[英]MySQL Do multiple counts with different WHERE clause and seeing the result
I am trying to get from my orders table: the number of orders each customer has placed within a week, then do another count for the next week, then again, and again, etc. 我正在尝试从订单表中获取:每个客户在一周内下的订单数量,然后在下周进行另一个计数,然后一次又一次,依此类推。
I am using COUNT but it keeps bringing back an empty result. 我正在使用COUNT,但它一直带回一个空结果。
Here is my query. 这是我的查询。
SELECT `uid`, (SELECT COUNT(`uid`) FROM `orders` WHERE `order_timestamp` > '1476707688' and `order_timestamp` < '1476189288') as 'number1',
(SELECT COUNT(`uid`) FROM `orders` WHERE `order_timestamp` > '1476189288' and `order_timestamp` < '1475584488') as 'number2',
(SELECT COUNT(`uid`) FROM `orders` WHERE `order_timestamp` > '1475584488' and `order_timestamp` < '1474979688') as 'number3'
FROM `orders` ORDER BY `uid` ASC
The result looks like this: 结果看起来像这样:
I know that there are multiple orders in a week from multiple customers. 我知道一周内有多个客户下订单。
How do you do that query? 您如何查询? A query that will bring back the number of orders a customer has made in that time period?
查询将带回该时间段内客户的订单数量?
Cheers, 干杯,
Just use conditional aggregation: 只需使用条件聚合:
SELECT `uid`,
SUM(`order_timestamp` > '1476707688' and `order_timestamp` < '1476189288') as number1,
SUM(`order_timestamp` > '1476189288' and `order_timestamp` < '1475584488') as number2,
SUM(`order_timestamp` > '1475584488' and `order_timestamp` < '1474979688') as number3
FROM `orders`
GROUP BY `uid` ASC;
Note: this aggregates by uid
, so there will be one row per uid
rather than per order. 注意:这是通过
uid
聚合的,因此每个uid
而不是每个订单)只有一行。 That seems like the sensible thing to do. 这似乎是明智的做法。
Can you please try as follow? 您可以尝试以下操作吗?
SELECT * FROM {table} WHERE date > DATE_SUB(NOW(), INTERVAL 1 DAY) ORDER BY uid DESC;
SELECT * FROM {table}WHERE date > DATE_SUB(NOW(), INTERVAL 1 WEEK) ORDER BY uid DESC;
SELECT * FROM {table}WHERE date > DATE_SUB(NOW(), INTERVAL 1 MONTH) ORDER BY uid DESC;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.