2013-02-26 176 views
2

我有一個要求,其中我有3個表SQL查詢與逗號分隔值

的ContactInfo

idContactinfo FirstName Lastname  idCOmpanyid 
--------------------------------------------------- 
1    Blah1  Blah1   1 
2    Blah2  Blah2   1 
3    Blah3  Blah3   1 
4    Blah4  Blah4   1 

ContactRole

idcontactrole  IdContactRoleName  idContactInfo 
------------------------------------------------------ 
1      1      1 
2      1      2 
3      1      3 
4      2      4 

IdContactRoleLookup

idcontactRole   RoleName 
---------------------------------- 
1      Admin 
2      Secretary 

我需要一個查詢,讓我這個樣子

idcontactrolename   Contacts 
-------------------------------------------------------- 
Admin     Blah1,Blah1;Blah2,Blah2,Blah3,Blah3 
Secretary    Blah4,Blah4 

結果這是我到現在爲止!

SELECT l.sValue 
    , SUBSTRING((
         SELECT C.sLast + ',' + C.sFirst + ';' 
         FROM contactinfo c 
         inner join contactrole crole 
         ON crole.idcontactinfo = c.idcontactinfo 
         WHERE crole.idcompany = '<<blah>>' 
         and c.idcompany = '<<blah>>' 
         FOR XML PATH('') 

        ), 1, 1000000) 
FROM CONTACTROLE CR 
inner join contactinfo c on 
cr.idcontactinfo = c.idcontactinfo 
inner join lookupdata l on cr.idlookuprole = l.idlookupdata 
where c.idcompany = '<<blah>>' 
+0

您的查詢,您的表定義不匹配?哪個是正確的? – sgeddes 2013-02-26 16:03:04

回答

1

我會做somethng這樣的,在您使用主查詢的ID即可SUBQUERY

SELECT  
l.sValue 
    , SUBSTRING((
         SELECT C.sLast + ',' + C.sFirst + ';' 
         FROM contactinfo c 
         inner join contactrole crole 
         ON crole.idcontactinfo = c.idcontactinfo 
         WHERE c.idcompany = '<<blah>>' 
AND c.idcontactrole = CR.idcontactrole 
         FOR XML PATH('') 

        ), 1, 1000000) 

FROM CONTACTROLE CR 
inner join lookupdata l on cr.idlookuprole = l.idlookupdata 

這會給大家一個COMPAGNIE的作用。如果角色不存在,您將有一個NULL值。

2
SELECT 
    RoleName, 
    STUFF(
     (
      SELECT ';' + b.FirstName + ', ' + b.LastName 
      FROM ContactRole a 
      INNER JOIN ContactInfo b 
        ON a.idContactInfo = b.idContactinfo 
      WHERE a.IdContactRoleName = r.idcontactRole 
      FOR XML PATH ('')) 
      , 1, 1, '') AS NamesList 
FROM IdContactRoleLookup r 
GROUP BY idcontactRole, RoleName 
1

您可以使用CROSS APPLY得到結果:

select distinct l.RoleName, 
    left(list, len(list) -1) list 
FROM CONTACTROLE CR 
inner join IdContactRoleLookup l 
    on cr.IdContactRoleName = l.idcontactRole 
cross apply 
(
    select C1.Lastname + ',' + C1.FirstName + ';' 
    from CONTACTROLE CR1 
    inner join contactinfo c1 
    on cr1.idContactInfo = c1.idContactinfo 
    where cr.IdContactRoleName = cr1.IdContactRoleName 
    FOR XML PATH('') 
) t2 (list) 

SQL Fiddle with Demo