按类别分组的返回计数包含该类别的项目

时间:2012-03-21 13:41:10

标签: sql sql-server sql-server-2005

我有一个表变量,其中包含以下条目:

locationID locationIDsub codetype code       codeTitle
---------- ------------- -------- ---------- ---------------
24         15            08       000000     Scooters
51         15            08       000000     Scooters
51         15            08       110000     Trucks
24         15            08       110000     Trucks
51         15            08       111011     Semis
24         15            08       111011     Semis
24         15            08       119061     Dump Trucks
24         15            08       119071     Garbage Trucks
51         15            08       254011     Cars

我想要的是:

occcode    occtitle               count locationID
---------- ---------------------- ----- ---------
000000     Scooters               2     24,51
110000     Trucks                 2     24,51
111011     Semis                  2     24,51
119061     Dump Trucks            1     24
119071     Garbage Trucks         1     24
254011     Cars                   1     51

我能够很好地计算,只是无法使用以下内容获取计数+ locationID列表:

SELECT Res.code,Res.codetitle,count(Res.codetitle)
FROM @resultsTable As Res
JOIN [dbo].[mv_VEHCODE_Union] As Veh
    ON Res.code= Veh.code AND Res.codetype = Veh.vehcodetype
GROUP BY Res.code,Res.codetitle
ORDER BY code

这是最终版本(仍在调整)我将根据Denis的回答(因为仅用于调试而删除了计数列):

select distinct 
    v.code, 
    v.codetype, 
    locations = stuff((
         select distinct ',' + cast(locationid as varchar) 
         from @resultsTable v2 
         where v2.code=v.code and v2.codetype = v.codetype 
         for xml path('')
    ),1,1,'') 
    from @resultsTable v
    order by v.code

1 个答案:

答案 0 :(得分:1)

你去了

select distinct 
v.code, 
v.codetype, 
cnt = (
     select count(*) 
     from mv_VEHCODE_Union v2 
     where v2.code=v.code and v2.codetype = v.codetype
), 
locations = stuff((
     select distinct ',' + cast(locationid as varchar) 
     from mv_VEHCODE_Union v2 
     where v2.code=v.code and v2.codetype = v.codetype 
     for xml path('')
),1,1,'') 
from mv_VEHCODE_Union v
order by v.code