Select s.FirstName, glTitle.LookupItem Title
from ClientStaff cs
left outer join Staff s on s.Id = cs.StaffId
left outer join StaffTitle st on st.StaffId = s.Id
left outer join GeneralLookup glTitle on glTitle.Id = st.glTitleId
返回以下行:
如您所见,第一列包含所有相同的行,因为一个员工可以拥有多个标题。
如何将每位员工的所有标题合并为逗号分隔值,以便每位员工只有一行?
答案 0 :(得分:3)
这对我有用:
;with mycte as
(select s.FirstName, glTitle.LookupItem Title
from ClientStaff cs
left outer join Staff s on s.Id = cs.StaffId
left outer join StaffTitle st on st.StaffId = s.Id
left outer join GeneralLookup glTitle on glTitle.Id = st.glTitleId
group by FirstName, glTitle.LookupItem)
SELECT Distinct FirstName, Titles = Replace(Replace(( SELECT title AS [data()] FROM mycte a
WHERE a.FirstName = b.FirstName
ORDER BY a.title FOR XML PATH ),'</row>',', '),'<row>','')
FROM mycte b
ORDER BY FirstName
答案 1 :(得分:1)
我通常会创建SQL函数并从查询中调用它们。您可以使用多种方法创建以逗号分隔的值列表,请参阅http://blog.sqlauthority.com/2008/06/04/sql-server-create-a-comma-delimited-list-using-select-clause-from-table-column/,Can I Comma Delimit Multiple Rows Into One Column?。
在这种情况下,如果您创建一个函数,则可以从SQL查询中调用它。类似的东西:
select s.FirstName, dbo.GetAllJobTitlesForStaff(s.Id) AS AllJobTitles
from ClientStaff cs
left outer join Staff s on s.Id = cs.StaffId
答案 2 :(得分:0)
这是标准SQL中难以(或不可能)执行的操作之一。许多供应商已经扩展SQL以支持这样的“汇总”;不幸的是,每个供应商的语法都不同。对不起,我目前没有方便的例子。那你使用什么DBMS?
答案 3 :(得分:0)
尝试类似:
select s.FirstName, GROUP_CONCAT(glTitle.LookupItem Title, ',')
from ClientStaff cs
left outer join Staff s on s.Id = cs.StaffId
left outer join StaffTitle st on st.StaffId = s.Id
left outer join GeneralLookup glTitle on glTitle.Id = st.glTitleId
GROUP BY s.FirstName
无法真正测试,所以它的困难,踪迹和错误通常最终会起作用。我建议按照一个独特的ID分组。
我希望这会有所帮助......
答案 4 :(得分:0)
您可以使用此查询。我有这样的查询的通用模板,遵循这种模式。您可能必须调试它,因为我没有您的表结构。它将标题合并为一个列表
DECLARE @List varchar(2000), @otherList varchar(2000),@FirstName varchar(2000),@id varchar(2000)
declare @temp table(
firstName varchar(128),
title varchar(4000)
)
DECLARE TitleList CURSOR FAST_FORWARD FOR
select s.FirstName, s.Id
from ClientStaff cs
left outer join Staff s on s.Id = cs.StaffId
OPEN TitleList
FETCH NEXT FROM TitleList INTO @FirstName,@id
WHILE @@FETCH_STATUS = 0
BEGIN
select @List = COALESCE(@List + ',', '') + Cast(glTitle.LookupItem As varchar(400))
from StaffTitle st
left outer join GeneralLookup glTitle on glTitle.Id = st.glTitleId
where st.StaffId = id
insert into @temp
select @FirstName,@List
set @List = null;
FETCH NEXT FROM TitleList INTO @FirstName,@id
END
CLOSE TitleList
DEALLOCATE TitleList
select * from @temp
答案 5 :(得分:0)
select
s.FirstName,
stuff((select ', '+glTitle.LookupItem
from StaffTitle as st
inner join GeneralLookup as glTitle
on glTitle.Id = st.glTitleId
where st.StaffId = s.Id
for xml path(''), type).value('text()[1]', 'nvarchar(max)'), 1, 2, '') as Title
from Staff as s