如何显示最高订单数i,e在表(tcount)中,客户名称(名称)

时间:2016-03-23 14:00:29

标签: mysql

我创建了2个表:customers(table1)和orderss(table2)

在表1中,我创建了columns(id,name),在表2中,我创建了columns(oid,customer_id,amount)

接下来,我使用sum()函数获取特定客户的总金额,并使用count()获取特定客户订购的总订单数量,并使用group by分别显示

现在我不知道如何找到具有特定客户名称的最高订单。

这就是我的尝试:

select max(name) as aaa,max(tcount) as highorders
from
   ( SELECT name,sum(orderss.amount) AS tamount,count(orderss.oid) as tcount
     FROM customers
     INNER JOIN orderss ON customers.id=orderss.customer_id group by name
     having tamount > 50 and tcount >= 2
   ) as ho

1 个答案:

答案 0 :(得分:0)

使用order by

select max(name) as aaa,max(tcount) as highorders
from
   ( SELECT name,sum(orderss.amount) AS tamount,count(orderss.oid) as tcount
     FROM customers
     INNER JOIN orderss ON customers.id=orderss.customer_id group by name
     having tamount > 50 and tcount >= 2
   ) as ho
order by field_name DESC

(您可以通过将ASC替换为ASC来获得升序