按用户花费的金额选择SUM用户

时间:2017-01-14 12:24:27

标签: mysql sum

所以我的表orders具有以下结构:

id | user_id | order_amount | time_started | status

我正在努力让那些自给定时间戳(包括users表)以来花费最多的用户访问他们的信息。

SELECT SUM(DISTINCT 'orders.order_amount') as 'amount_total' FROM 'orders' LEFT JOIN 'users' ON 'orders.user_id' = 'users.id' WHERE 'orders.time_started' >= "1484396552" AND 'orders.status' = 1 ORDER BY 'amount_total' GROUP BY 'orders.user_id' DESC

但此查询无效。我期望的结果是:

id | user_id | amount_total | user_data_from_users | user_data_from_users...

1 个答案:

答案 0 :(得分:1)

可能是因为很多语法错误,例如

  • 单引号而不是反引号`
  • 按分组前排序
  • DESC已添加到

试试这个:

SELECT `orders`.`user_id`,SUM(`orders`.`order_amount`) AS `amount_total`, `users`.*
FROM `orders`
LEFT JOIN `users`
ON `orders`.`user_id`          = `users`.`id`
WHERE `orders`.`time_started` >= 1484396552
AND `orders`.`status`          = 1
GROUP BY `orders`.`user_id`
ORDER BY `amount_total` DESC;