获取SQL中出现的多个列的计数

获取SQL中出现的多个列的计数,sql,sql-server,sql-server-2012,Sql,Sql Server,Sql Server 2012,有一个关于我试图使用SQL Server 2012编写的查询的问题。我有一个表,其中有两列(Agent和UN),我正在关注。我想找出代理和取消发生的次数。例如,在下表中: +----+-------+----+ | ID | Agent | UN | +----+-------+----+ | 1 | 27 | 1 | | 2 | 28 | 1 | | 3 | 27 | 1 | | 4 | 27 | 2 | | 5 | 28 | 2 | | 6

有一个关于我试图使用SQL Server 2012编写的查询的问题。我有一个表,其中有两列(Agent和UN),我正在关注。我想找出代理和取消发生的次数。例如,在下表中:

+----+-------+----+
| ID | Agent | UN |
+----+-------+----+
| 1  | 27    | 1  |
| 2  | 28    | 1  |
| 3  | 27    | 1  |
| 4  | 27    | 2  |
| 5  | 28    | 2  |
| 6  | 28    | 2  |
+----+-------+----+
一个例子与此类似:

+-------+--------+----+
| Count | Agent  | UN |
+-------+--------+----+
|     2 |     27 |  1 |
|     2 |     28 |  2 |
|     1 |     27 |  2 |
|     1 |     28 |  1 |
+-------+--------+----+
ID不重要,我只想知道Agent和UN作为成对出现的位置及其计数

我的尝试就是这样。我必须对每个代理都这样做,然后将它们结合起来,但我认为可能有一种更快的方法来实现这一点

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

您应该
取消
代理
分组,然后
计数
重复项。要检索
Agent
列中所有可能值的数据,应删除
WHERE
子句:

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

您应该
取消
代理
分组,然后
计数
重复项。要检索
Agent
列中所有可能值的数据,应删除
WHERE
子句:

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

按代理和UN分组,并从where子句中取出条件,以获取所有组的计数

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

按代理和UN分组,并从where子句中取出条件,以获取所有组的计数

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

试一试


您需要按代理和联合国进行分组

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

您需要按代理和联合国进行分组

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

这应该可以解决问题:

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

这应该可以解决问题:

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

看起来你想要的是:

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

这会给你你想要的东西。

看起来你想要的是:

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

这会给你你想要的东西。

如果你解释你所做的改变会更好。如果你解释你所做的改变会更好。