我有两张桌子。用户和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在这里
答案 0 :(得分:1)
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
答案 1 :(得分:0)
对于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 = ?;