Question

Have a question about a query I am attempting to write, using SQL Server 2012. I have a table with 2 columns (Agent and UN) I am focusing on. I would like to find the number off occurrences that Agent and UN occur. For example, in the table below:

+----+-------+----+
| ID | Agent | UN |
+----+-------+----+
| 1  | 27    | 1  |
| 2  | 28    | 1  |
| 3  | 27    | 1  |
| 4  | 27    | 2  |
| 5  | 28    | 2  |
| 6  | 28    | 2  |
+----+-------+----+

An example would look similar to this:

+-------+--------+----+
| Count | Agent  | UN |
+-------+--------+----+
|     2 |     27 |  1 |
|     2 |     28 |  2 |
|     1 |     27 |  2 |
|     1 |     28 |  1 |
+-------+--------+----+

The ID does not matter, I just want to get where Agent and UN occur as pairs and their counts.

My attempt was this. I would have to do this for every agent and then combine them, but I'm thinking there is probably a quicker way to accomplish this?

select count(UN) as Count, Agent, UN 
Where Agent = 27
group by UN
order by count(UN) desc
Was it helpful?

Solution

Group by both agent and UN, and take out the condition from the where clause, to get the count for all groups.

select      count(*), agent, un
from        tbl
group by    agent, un
order by    1 desc

OTHER TIPS

You should GROUP BY UN and Agent and then COUNT duplicates. To retrieve data for all possible values in Agent column you should remove your WHERE clause :

SELECT COUNT(*) as Count
     , Agent
     , UN 
FROM table
GROUP BY UN
       , Agent
ORDER BY COUNT(*) DESC

You need to group by both Agent and UN

 select count(*) as Count, Agent, UN 
 from tbl
 group by Agent, UN
 order by Count(*) desc

Try

select Frequency = count(*) ,
       Agent     = t.Agent  ,
       UN        = t.UN
from dbo.my_table t
group by t.Agent , t.UN
order by count(*) desc, t.Agent , t.UN

This should fix the problem:

select count(*) as Count, Agent, UN 
from Agent
group by Agent, UN
order by count(*) desc

It looks like you want is:

select count(UN) as Count, Agent, UN 
group by Agent, UN
order by count(UN) desc

This should give you what you are looking for.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top