2014-02-11 45 views
-1

我有四個表僱員,association_employees,協會,association_items。 下面的select查詢爲我提供了連接的行。通過將列填充到列表中來組合多行。

注意:我已經爲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 

正如可以注意到,存在從 '項目值' 列開類似的多個行。 我需要結合這些行來產生以下結果。

最少報名輸出

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

那麼,爲什麼倒票? – RRK

回答

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, 

這has't被測試,因此可能需要一些微調。

3

如果您需要ColdFusion解決方案,cfoutput的組屬性將起作用。步驟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列表中排除尾隨分號。

+0

我更新了這個刪除額外的'query'屬性並給出了一個分隔列表。 –

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>