views:

302

answers:

2

Given the following query, how do I return the p_name with the most transactions? And similarly, how do I return the t_amount with the most transactions. I'd like to do it all in this one query of course.

SELECT t.*, p.* 
FROM transactions t
LEFT JOIN partners p ON p.id=t.partner_id

which can return something like:

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

So given that result set, I'd get back best_partner = simmons and also best_amount = 100.00

Thanks!

A: 
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
W_P
"GROUP BY p_count" is wrong, you'll have an error message see reponse from @Kjetil
remi bourgarel
A: 

I assume "best partner"= the parner with the highest number of transactions and "best amount" = the most frequently occurring transaction amount.

To count the transactions you can use the Count() function and group by. Something like this:

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

Similar for "best amount":

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

Edit: Combined as two sub queries:

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
Kjetil Watnedal
No way to combine the 2 queries?
k00k
SELECT t.amount,p.name, Count(t.id) as transactionAmountCountFROM transactions tLEFT JOIN partners p ON p.id=t.partner_idGROUP BY t.amount,p.nameORDER BY 3 DESC LIMIT 1
remi bourgarel
@remi, what does the ORDER BY 3 do? More directly, what is the 3 referring to?
k00k
@k00k (myself), 3 refers to the 3rd column.
k00k
@k00k: I don't think you can do this in one single query, but you can avoid the roundtrip to the database by running two sub queries. I'll add it to my answer.
Kjetil Watnedal
@remi: Your query will give the partner with the highest number of any transaction amount, but there may be an amount occurring more frequently distributed over transactions for different partners.
Kjetil Watnedal
@Kjetil you're right
remi bourgarel