在一个查询中生成许多count()

时间:2016-03-21 11:32:46

标签: sql sql-server sql-server-2008

我有呼叫客户的数据集,我想让count()知道: 每个客户的总呼叫数 每个客户的总呼叫持续时间 客户所在的位置总数

这是我的数据:

Phone no. - Duration In minutes - Location

1111            3                     88
2222            4                     33
3333            4                     4
1111            7                     55
3333            9                     4
3333            7                     3

查询结果:

phone no- Total number of records -Total duration of calls- Total of location

1111              2                          10                   2
2222              1                           4                   1
3333              3                           20                  2

4 个答案:

答案 0 :(得分:0)

您可以将GROUP BY查询与基本聚合函数一起使用,如COUNT(),SUM()和COUNT(DISTINCT),如下所示:

select phone_no, count(*), sum(duration), count(distinct location)
from tablename
group by phone_no

答案 1 :(得分:0)

这与fthiella的回答几乎相似。试试这个

select PhoneNo,
count(*) as TotalNumberOfRecords, 
sum(DurationInMinutes) as TotalDurationOfCalls,
count(distinct location) as TotalOfLocations from yourtablename
group by PhoneNo

答案 2 :(得分:0)

回答你的问题是

select Phone no,count(Duration In minutes),sum(Duration In minutes),count(distinct Location) from Tablename group by Phone no order by Phone no;

答案 3 :(得分:0)

我已经制作了临时表进行测试,它提供了与你提到的相同的输出。看下面的查询:

declare @TEMP table (phone_no int, duration int, location int)
insert into @temp values(1111,3,88),(2222,4,33),(3333,4,4),(1111,7,55),(3333,9,4),(3333,7,3)

select phone_no, count(*), sum(duration), count(distinct location)
from @TEMP
group by phone_no

你可以考虑这个问题:

select phone_no, count(*), sum(duration), count(distinct location)
from @TEMP
group by phone_no