我有四个表员工,associations_employees,association,association_items 。 下面的选择查询会生成连接的行。
注意:我为SQL和Coldfusion语言制作了标签,这是因为我使用coldfusion作为我的脚本语言。我不确定我是应该依赖SQL还是使用我的脚本语言。
查询
SELECT AE.userid, E.firstname,
A.title, AI.itemvalue
FROM associations_employees AE INNER JOIN
employees E on E.userid = AE.useridFK INNER JOIN
associations A on A.associationid = AE.associationidFK INNER JOIN
association_items AI on AI.associationidFK = AE.associationidFK
当前选择输出
userID firstname title itemvalue
------ --------- ----- ---------
5603 Jesh Learner Type Family Literacy
5603 Jesh Learner Type Elementary School
5603 Jesh Learner Type Academic
5603 Jesh Personnel Type Staff
5605 jennone Personnel Type Site Supervisor
5605 jennone Personnel Type Rops member
5607 Sharon Personnel Type Rops member
5607 Sharon Personnel Type Site Supervisor
5607 Sharon Mentor Type High School
5607 Sharon Mentor Type Op. Read
5607 Sharon Mentor Type Enrichment
5607 Sharon Mentor Type General
正如您所注意到的,除了'itemvalue'列之外,还有多行类似。 我需要组合这些行以产生以下结果。
需要的输出
userID firstname title itemvalue
------ --------- ------ ---------
5603 Jesh Learner Type Family Literacy;Elementary School;Academic
5603 Jesh Personnel Type Staff
5605 jennone Personnel Type Rops member;Site Supervisor;Staff
5607 Sharon Personnel Type Rops member;Site Supervisor
5607 Sharon Mentor Type Enrichment;General;High School;Op. Read
答案 0 :(得分:4)
您可以使用STUFF方法来实现此目的:
SELECT AE.userid,
E.firstname,
A.title,
STUFF((SELECT ',' + [AI.itemvalue]
FROM association_items AI
WHERE AI.associationidFK = AE.associationidFK
FOR XML PATH('')), 1, 1, '') AS itemvalue
FROM associations_employees AE
INNER JOIN employees E ON E.userid = AE.useridFK
INNER JOIN associations A ON A.associationid = AE.associationidFK
GROUP BY AE.userid, E.firstname, A.title,
这尚未经过测试,因此可能需要进行一些微调。
答案 1 :(得分:3)
如果您需要ColdFusion解决方案,cfoutput的group属性将起作用。第1步是在查询中添加order by子句。
order by userid, title
接下来,你的cfoutput标签。
<cfoutput query="yourquery" group = "userid">
<cfoutput group = "title">
#userid # #firstname# #lastname# #title#
<cfset items = ''>
<cfoutput>
<cfset items = listappend(items,itemvalue,';')>
</cfoutput>
#items#
</cfoutput>
</cfoutput>
这是基本方法。您必须添加格式以及如何从itemvalue列表中排除尾部分号。
答案 2 :(得分:2)
你可以使用类似于Dan的数组方法。数组可能更快
<cfoutput query="yourquery" group = "userid">
<cfoutput group = "title">
#userid # #firstname# #lastname# #title#
<cfset items = []>
<cfoutput>
<cfset ArrayAppend(items, itemvalue)>
</cfoutput>
#ArrayToList(items, ";")#
</cfoutput>
</cfoutput>