获取SQL中多列出现次数

时间:2014-05-13 23:23:02

标签: sql sql-server sql-server-2012

使用SQL Server 2012对我正在尝试编写的查询提出疑问。我有一个包含2列(代理和UN)的表我正在关注。我想找到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

6 个答案:

答案 0 :(得分:4)

由代理人和联合国分组,并从where子句中取出条件,以获得所有组的计数。

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

答案 1 :(得分:2)

您应该GROUP BY UNAgent,然后COUNT重复。要检索Agent列中所有可能值的数据,您应删除WHERE子句:

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

答案 2 :(得分:1)

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

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

答案 3 :(得分:0)

尝试

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

答案 4 :(得分:0)

这应解决问题:

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

答案 5 :(得分:0)

看起来你想要的是:

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

这可以为您提供所需的信息。