如何加入id出现而不是简单地显示count(*)?

时间:2016-03-22 19:39:13

标签: sql sql-server tsql

我做了这个代码片段来演示:http://sqlfiddle.com/#!6/ed243/2

架构:

create table professional(
  id int identity(1,3) primary key,
  name varchar(20)
)
insert into professional values('professional A')
insert into professional values('professional B')
insert into professional values('professional C')

create table territory(
  id int identity(2,3) primary key,
  name varchar(20)
)
insert into territory values('territory A')
insert into territory values('territory B')
insert into territory values('territory C')

create table panel(
  id int identity(3,3) primary key,
  idProfessional int not null,
  idTerritory int not null,
)
insert into panel values(1, 2)
insert into panel values(4, 5)
insert into panel values(7, 8)
insert into panel values(1, 5)
insert into panel values(7, 8)
insert into panel values(7, 2)

到目前为止我的查询:

select 
    p.id, p.name, count(*) as Territories
from 
    (select distinct idProfessional, idTerritory from panel) panel
inner join
    professional p 
    on p.id = panel.idProfessional
group by 
    p.id, 
    p.name
having count(*) > 1
order by p.id

上述查询显示每个专业使用 distinct 进行过滤的区域数量,以及仅显示在拥有的多个区域内工作的专业人员

-------------------------------------------------------
|    id    |    name              |    Territories    |
-------------------------------------------------------
|    1     |    professional A    |    2              |
|    7     |    professional C    |    2              |
-------------------------------------------------------

好的,但是..是否可以在Territories每个 idTerritory 加入,如"2, 5"而不是count(*)

提前致谢。

1 个答案:

答案 0 :(得分:1)

如果有必要,我通常使用FOR XML函数来执行多行的这种连接。我认为这个查询可以满足您的需求:

select 
    p.id, p.name, STUFF(
        (select ', ' + CAST(t.id AS VARCHAR(10))
         from panel panel2
         inner join territory t
            ON t.id = panel2.idTerritory
         where panel2.idProfessional = p.id
         order by t.name
         for xml path(''), root('XMLVal'), type 
     ).value('/XMLVal[1]','varchar(max)') 
   , 1, 2, '') as Territories
from panel
inner join
    professional p
    on p.id = panel.idProfessional
group by
    p.id,
    p.name
having count(*) > 1
order by p.id

我使用此博客创建了我的答案:http://blogs.lobsterpot.com.au/2010/04/15/handling-special-characters-with-for-xml-path/