我有两张桌子。用户和transactions.lets说类型1是学生,类型2是教师
用户:
+----+--------+--------------+
| id | name | user_type_id |
+----+--------+--------------+
| 1 | Noob | 1 |
| 2 | Coder | 2 |
+----+--------+--------------+
交易方式:
+----+---------+--------+
| id | user_id | amount |
+----+---------+--------+
| 1 | 1 | 10 |
| 2 | 2 | 10 |
| 3 | 1 | 10 |
+----+---------+--------+
我想获得每个user_type_id的总和和计数;像这样的东西
user_type_id:1
sum_of_transaction: 20,
number_of_transactions: 2,
user_type_id:2
sum_of_transaction: 10,
number_of_transactions: 1
我怎样才能做到这一点? Noob在这里
select aa.user_type_id, sum(bb.amount) as sum_of_transaction,
count(bb.id) as number_of_transactions
from users aa inner join transactions bb on aa.id = bb.user_id
group by aa.user_type_id
对于sum_of_transaction:select sum(amount) as sum_of_transaction from transactions where user_id = ?;
对于number_of_transactions:select count(amount) as number_of_transactions from transactions where user_id = ?;