【问题标题】:Grabbing last order date, total orders and total amount with one query?一次查询获取最后下单日期、总订单和总金额?
【发布时间】:2013-10-22 11:22:46
【问题描述】:

我最初计划使用多个查询和一些 PHP 来执行此操作。

我想做的是获取特定用户上次下订单的时间,用户总共有多少订单,以及他支付的总金额/成本/计数是多少。

我试过的是这个 SQL:

SELECT `orders`.`date_created`, 
SUM(total_count) as total_sum, 
COUNT(id) AS total_orders 
FROM `orders` 
WHERE `user_id` = '96838' 
AND (`status` = 'new' OR `status` = 'delivered') 
ORDER BY `orders`.`date_created` DESC
LIMIT 1

我对上面的期望是:

total_sum = total count/amount of all the orders that the user has.
total_orders = total orders
date_created = grab the last orders date_created, so we can know when the last time was.

当我今天运行上述 SQL 时,我确实收到了正确的 total_sum 和 total_orders 值,但 date_created 是错误的(它选择第一个订单而不是最后一个?)

那么“LIMIT 1”有必要吗?

【问题讨论】:

  • 如果以下答案不能解决您的问题,请考虑提供适当的 DDL 和/或 sqlfiddle 以及所需的结果集。

标签: mysql sql


【解决方案1】:

如果我了解您的需求,则无需分组 - 只需获取最大日期即可:

SELECT
    MAX(date_created) as last_order_date, 
    SUM(total_count) as total_sum, 
    COUNT(id) AS total_orders 
FROM
    `orders` 
WHERE
    `user_id` = '96838' 
    AND
    `status` IN ('new', 'delivered')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-23
    • 1970-01-01
    • 2017-07-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多