简体   繁体   English

从同一行的不同表中选择SELECT SUM和COUNT,PHP和MySql

[英]SELECT SUM and COUNT, FROM different tables on same row, PHP and MySql

I got 3 tables, transactions , clubs and clients , a Club can have only one salesman, and each Client can belong to only one Club, the clients make payments in the transactions table. 我有3个表, transactionsclubsclients ,一个Club只能有一个推销员,每个客户只能属于一个Club,客户在交易表中付款。

I'm trying to get a list of all Salesman, how many payments per Club and the total amount of payment per Club on a specific date. 我正在尝试获取所有推销员的列表,每个俱乐部在特定日期的付款额以及每个俱乐部的付款总额。

I only get one row, with the first salesman, and the total for everyone, don't know how to get each row with the totals of each individual Salesman. 我只有第一行推销员得到一排,每个人的总数却不知道如何将每一行推销员的总数与每一行相提并论。 Thank you for your time. 感谢您的时间。

+--------------------------------------------+
|                transactions                |
+--------------------------------------------+
| id_transaction | date | amount | client_id |
+----------------+------+--------+-----------+

+------------------------------+
|            clients           |
+------------------------------+
| id_client | name | club_name |
+-----------+------+-----------+

+-----------------------------------+
|               clubs               |
+-----------------------------------+
| id_club | name_club | name_seller |
+---------+-----------+-------------+

SELECT 
   transactions.amount,
   clients.id_client,
   clubs.club_name,
   club.name_seller,
   SUM(transactions.amount) AS sum_amount,
   COUNT(transactions.amount) AS count_amount,
   club.name_seller AS salesman
FROM transactions, members, clubs
WHERE transactions.date = '$date' 
AND clients.id_client = transactions.client_id 
AND client.club_name = clubs.name_club 


 <th>Salesman</th>
 <th>Club Name</th>
 <th>Number of Transactions</th>
 <th>Total amount</th>   

 $output.='<td>'.$row['salesman'].'</td>';
 $output.='<td>'.$row['club_name'].'</td>';
 $output.='<td>'.$row['COUNT(amount)'].'</td>';
 $output.='<td>'.$row['SUM(amount)'].'</td>';

This is what I'm trying, Example: 这就是我正在尝试的示例:

Salesman - Club name - Number of Transactions - Total amount 推销员-俱乐部名称-交易数-总金额
Bill - TennisClub - 5 - 5000 Bill - Golf Club - 7 - 7000 Joe - Pool Cub - 2 - 2000 比尔-TennisClub-5-5000比尔-高尔夫俱乐部-7-7000乔-台球崽-2-2000

You have to use Group By statement in your query ( If you want salesman based, You can put salesman id ) 您必须在查询中使用Group By语句(如果要基于销售员,则可以输入销售员ID)

I think, you have changed the table structure names before posting the question. 我认为,您在发布问题之前已经更改了表结构名称。 So, I can't understood the Primary & Foreign key's. 因此,我无法理解主键和外键。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM