我有一個包含類似條目表變量:返回計數分組按類別隨着項目包含種類
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
我能夠得到計數很好,只是無法使用以下方法獲得位置ID的計數+列表:
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
下面是最終版本(仍在調整)我與基於丹尼斯的回答會(我放棄了數列,因爲僅用於調試):
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
看到這個問題的答案:http://stackoverflow.com/questions/451415/simulating-group-concat-mysql-function-in-ms-sql-server-2005 – 2012-03-21 13:45:33
好吧,看看接受的答案中的示例我我仍然沒有看到如何實際顯示正確的結果。我得到的仍然是2行(每個locationID),但locationID列表列有'24,24,24,24,24,24,24,24,...'或'51,51,51,51 ,51,51,51,51,......「。從本質上講,每次出現代碼值都有1個locationID條目。 – wergeld 2012-03-21 14:18:26
你嘗試了什麼? – 2012-03-21 14:25:09