我有两个带连接表的主表。一个表具有所有主记录,第二个表具有与主记录相关联的类别。链接表。连接表具有来自类别和主记录的ID的条目,并且它构建关联(主记录id 2,以类别id 245为例)
我正在尝试构建一个输出所有主记录的查询,其中包含主记录的每一行的所有类别,因为某些行可以有许多类别。
我希望它能以分隔的方式输出它们,这样我就可以将它保存到每个主记录的一行。现在,我似乎能做的最好的事情就是主要项目的每个类别都有一行。我想要的例子(高度简化)。
ID | Name | Category
-------------------------------------
2 | thing | shiny,special,explosive
我现在得到的是:
ID | Name | Category
-------------------------
2 | thing | shiny
2 | thing | special
2 | thing | explosive
等。
这是我当前查询的状态 - 选择了这么多列的原因是表中有很多列,我只需要显示一些。
SELECT Attractions.ID
, Attractions.HotelName
, Attractions.Enabled
, Attractions.HotelAddress1
, Attractions.HotelAddress2
, Attractions.City
, Attractions.Prov
, Attractions.Country
, Attractions.PostalCode
, Attractions.Latitude
, Attractions.Longitude
, Attractions.Ratings
, Attractions.Phone
, Attractions.Fax
, Attractions.TollFree
, Attractions.Email
, Attractions.Website
, Attractions.ShowInSearch
, Attractions.MoreInfoCounter
, Attractions.ContactPerson
, Attractions.ContactPersonFirst
, Attractions.ContactPersonLast
, Attractions.Notes
, Attractions.SponsorID
, Attraction_Sub_Types.Name
FROM
dbo.Attractions_Attraction_Sub_Types_Link
INNER JOIN dbo.Attractions
ON Attractions_Attraction_Sub_Types_Link.AttractionID = Attractions.ID
INNER JOIN dbo.Attraction_Sub_Types
ON Attractions_Attraction_Sub_Types_Link.Sub_TypeID = Attraction_Sub_Types.ID
WHERE
Attractions.ShowInSearch = 1
ORDER BY
Attractions.ID
我最初尝试过子查询,但我永远无法得到一个验证,甚至从哪里开始,所以我放弃了。
答案 0 :(得分:0)
使用COALESCE
功能。尝试类似:
DECLARE @Category VARCHAR(8000)
SELECT @Category = COALESCE(@Category + ', ', '') + Category
FROM categories_table
WHERE Category IS NOT NULL
答案 1 :(得分:0)
这是如何执行此操作的示例:
select 'test' as Test, 1 as Item
into #test
union select 'test2', 2
union select 'test', 3
union select NUll, 4
union select 'test', 5
select t2.test, STUFF((SELECT ', ' + cast(t1.Item as varchar (10) )
FROM #test t1 where t2.test = t1.test
FOR XML PATH('')), 1, 1, '')
from #test t2
group by t2.test