There is a query in the database that I can not properly formulate (that would work adequately). There is an orders table in which there are customers id, and there are two more tables: customers and firms for which an order was made (mtm through another groups table, where there are id companies and customers). I need to select customers who have the largest number of orders and related firms and sort them by the number of (orders) in descending order ... while I struggle unsuccessfully. Can someone suggest?
Orders
| id | sum | date | customer_id |
Customers
| id | name | last_name | e_mail |
Firms
| id | name | e_mail |
Groups
| customer_id | firm_id |
The output should be:
Firms.name Customers.name COUNT (the number of orders given by Customers.name)
Ie, this client has the largest number of orders in general and the name of the company with which the largest number of links in Groups is coming, because as a single client, it can order for different companies and belong to different companies.
groups
- is amapping
(N to N) betweencustomer
andfirms
- MaxU