tags:

views:

59

answers:

3

MySQL 5.0.45

Table A has the following fields (columns): 1. transcation_id
2. client_name
3. item_id
4. .....

Now I need to find how many transactions each client has made order by # of transactions. The result should be like:

Tom 7 transactions
Jack 5 transactions
Mike 2 transactions

If a client has no transactions his name should not be int he list.

Thank you in advance!

+3  A: 
Select 
    Client_Name,
    count(*) as Transactions
from TableA
group by Client_Name
order by count(*) desc
Jose Chama
That should also have a `HAVING COUNT(*) != 0`.
Shtééf
@Shtééf: Thanks, actually it will count any existing record, assuming that if there are no transaction there will not be a record.
Jose Chama
This is also working. Thank you so much!
David
@Jose Chama: whoops, good point. :)
Shtééf
+4  A: 

How about:

select client_name, count(*) as transactions
from TableA
group by client_name
order by count(*) DESC

Assuming that clients without transactions aren't in the table (since the table has a transaction_id column) they won't be in the result.

Sean Carpenter
Works. Thank you!
David
this is correct, although I would do count(1) instead of count(*) slightly better performance, at least on Oracle there is difference.
Jay
+1  A: 

Something like this?

Select client_name, count(*) As MyCount
From YourTableA
Group By client_name
Having MyCount > 0
Order by MyCount Desc

Edit: grr, too slow again! At least I got the aliases in...

tijmenvdk