【问题标题】:Sql query to return information about customers which has spent the most amountSql 查询返回有关花费最多的客户的信息
【发布时间】:2021-01-07 19:08:44
【问题描述】:

我有一个关于商店的数据库,我需要返回花费最多的前 5 个客户的完整信息,并且在返回的结果中也显示该总金额。 (算上所有 他/她的付款一起从付款表)。按总金额降序排列。 有人可以帮忙查询吗?

客户表

付款表

【问题讨论】:

  • JOIN、GROUP BY、SUM、ORDER BY、LIMIT

标签: sql phpmyadmin


【解决方案1】:

应该是这样的。您可能需要尝试一下,但它会给您一个良好的开端。

SELECT c.CustomerName, SUM(p.amount) AS Total
FROM CustomersTable c
INNER JOIN PaymentsTable p
ON c.customerNumber = p.customerNumber
GROUP BY p.customerNumber DESC LIMIT 5

【讨论】:

  • hm,它告诉我我不能分组:(
  • 好的,等一下,我会尝试在我的一个数据库中运行它
  • 也许可以试试,我忘了加入表lol
  • MySQL 说:文档 #1054 - '字段列表'中的未知列 'customers.customerNumber'
  • 我修复了 #1054 但仍然抛出我无法在 Total 上分组的错误
【解决方案2】:

SELECT min(c.Customername), SUM(p.amount) AS Total 来自客户 c INNER JOIN 付款 p 关于 c.Customernumber=p.Customernumber

GROUP BY p.Customernumber 按 2 DESC 排序

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多