鉴于以下查询,如何返回具有最多事务的p_name?类似地,如何返回具有最多事务的t_amount。我当然希望在这一个查询中完成所有操作。
SELECT t.*, p.*
FROM transactions t
LEFT JOIN partners p ON p.id=t.partner_id
可以返回类似的内容:
t_amount t_platform t_user p_id p_name
100.00 windows 122 20 simmons
200.00 windows 211 20 simmons
100.00 mac 200 18 smith
100.00 linux 190 20 simmons
100.00 mac 100 18 smith
所以给定结果集,我会回来best_partner = simmons和best_amount = 100.00
谢谢!
答案 0 :(得分:1)
我认为“最佳合作伙伴”=交易数量最多的合伙人和“最佳金额”=最常发生的交易金额。
要计算事务,可以使用Count()函数和group by。像这样:
SELECT p.name,count(t.id) as transactionCount
FROM transactions t
LEFT JOIN partners p ON p.id=t.partner_id
GROUP BY p.name
ORDER BY 2 DESC
LIMIT 1
类似于“最佳金额”:
SELECT t.amount, Count(t.id) as transactionAmountCount
FROM transactions t
LEFT JOIN partners p ON p.id=t.partner_id
GROUP BY t.amount
ORDER BY 2 DESC
LIMIT 1
编辑:合并为两个子查询:
SELECT
(SELECT p.name
FROM transactions t
LEFT JOIN partners p ON p.id=t.partner_id
GROUP BY p.name
ORDER BY count(t.id) DESC
LIMIT 1) as best_partner
,
(SELECT t.amount
FROM transactions t
LEFT JOIN partners p ON p.id=t.partner_id
GROUP BY t.amount
ORDER BY Count(t.id) DESC
LIMIT 1) as most_occuring_transaction_amount
答案 1 :(得分:-3)
SELECT p.*, COUNT(p.id) AS p_count
FROM transactions t
LEFT JOIN partners p ON p.id=t.partner_id
GROUP BY p_count
ORDER BY p_count DESC
LIMIT 1