获取每个用户名获得的服务数量

时间:2011-12-23 10:29:27

标签: sql-server-2008

我有这张桌子:

    serviceID    Name     L_name    
  --------------------------------
        1         A         B      
        2         A         B
        3         C         D
        4         E         F 

我想得到每个人得到的服务数量:

         Name    L_Name    Countf
   ---------------------------------
          A         B        2
          C         D        1
          E         F        1  

这是我写的一个查询,但没有正确的结果集:

select * 
from  
(Select  Name,L_Name,COUNT(Service_ID) as 'countf' 
from Service_Tbl  
group by Name,L_Name) as tbl

我明白了:

         Name    L_Name    Countf
   ---------------------------------
          A         B        1
          A         B        1
          C         D        1
          E         F        1  

1 个答案:

答案 0 :(得分:1)

您需要group这样的结果:

select Name, L_Name, COUNT(Service_ID) as 'countf'
from Service_Tbl  
group by Name,L_Name

这是一个提供所需结果的完整示例:

create table #Service_Tbl  (
serviceID    int,
Name     varchar(1),
L_name    varchar(1)
)

insert into #Service_Tbl values (1, 'A','B')
insert into #Service_Tbl values (2, 'A','B')
insert into #Service_Tbl values (3, 'C','D')
insert into #Service_Tbl values (4, 'E','F')

select Name, L_Name, COUNT(ServiceID) as 'countf'
from #Service_Tbl  
group by Name,L_Name

drop table #Service_Tbl