将多个行值组合到一个列中

时间:2015-09-18 12:02:32

标签: sql sql-server xml

我很欣赏以前曾提出类似的问题,但我不确定下一步该尝试什么,并且面临一些压力。我正在尝试将多个行值组合到一个列中,为此我尝试使用XML Path。以下是我所要做的,但我现在只是在一个列中显示多个主题的多个实例。

使用SQL Server,我想将给定学生的所有科目(大约10个)组合到“所有科目”栏目中。有人能指出我哪里出错了吗?谢谢,加文

SELECT distinct
P.FORM AS Class, 
NAME.NAME AS [Pupil Name], 
(SELECT ';' + SS.DESCRIPTION
FROM PUPIL P 
INNER JOIN PUPIL_SET PS on PS.PUPIL_ID = P.PUPIL_ID
INNER JOIN SUBJECT_SET SS on SS.SUBJECT_SET_ID = PS.SUBJECT_SET_ID 
FOR XML PATH('')) [All Subjects],
NAME_1.TITLE + ' ' + NAME_1.FIRST_NAMES + ' ' + NAME_1.SURNAME AS [Parent or     Carer Name],
Replace(isnull(ADDRESS.HOUSE_STREET,'') + ', ' +     isnull(ADDRESS.VILLAGE_AREA,'') + ', ' + isnull(ADDRESS.TOWN_CITY,'') + ', ' +     isnull(ADDRESS.COUNTY,'') + ', ' + isnull(ADDRESS.COUNTRY,'') + ' ' +     isnull(ADDRESS.POST_CODE,''),',,', '') AS Address,
--RELATIONSHIP.RANK,
CASE WHEN NAME.MAIN_ADDRESS_ID = NAME_1.MAIN_ADDRESS_ID THEN 'HOME' ELSE    'OTHER' END AS [Home or Other]
FROM PUPIL P
INNER JOIN NAME ON P.NAME_ID = NAME.NAME_ID
INNER JOIN ADDRESS ON NAME.MAIN_ADDRESS_ID = ADDRESS.ADDRESS_ID
INNER JOIN RELATIONSHIP ON NAME.NAME_ID = RELATIONSHIP.FROM_NAME_ID
INNER JOIN NAME AS NAME_1 ON RELATIONSHIP.TO_NAME_ID = NAME_1.NAME_ID
INNER JOIN PUPIL_SET PS on PS.PUPIL_ID = P.PUPIL_ID
INNER JOIN SUBJECT_SET SS on SS.SUBJECT_SET_ID = PS.SUBJECT_SET_ID
WHERE 
(RELATIONSHIP.RANK=1 Or RELATIONSHIP.RANK=2) 
AND P.ACADEMIC_YEAR=YEAR(DateAdd(m,-5,getDate()))
AND P.SUB_SCHOOL='030SEN' 
AND P.IN_USE='y' 
AND P.RECORD_TYPE='1' 
AND Len(P.FORM)>0
and p.ACADEMIC_YEAR = 2015; 

1 个答案:

答案 0 :(得分:0)

首先,您只需要子查询中的subject_setpupil_set,而不是外部查询。

其次,您需要一个关联子句。所以,像这样:

SELECT P.FORM AS Class,
       . . .
       (SELECT ';' + SS.DESCRIPTION
        FROM PUPIL_SET PS INNER JOIN
             SUBJECT_SET SS
             on SS.SUBJECT_SET_ID = PS.SUBJECT_SET_ID 
        WHERE PS.PUPIL_ID = P.PUPIL_ID
        FOR XML PATH('')
       ) [All Subjects],
       . . .
FROM PUPIL P INNER JOIN
     NAME
     ON P.NAME_ID = NAME.NAME_ID INNER JOIN
     ADDRESS
     ON NAME.MAIN_ADDRESS_ID = ADDRESS.ADDRESS_ID INNER JOIN
     RELATIONSHIP
     ON NAME.NAME_ID = RELATIONSHIP.FROM_NAME_ID INNER JOIN
     NAME AS NAME_1
     ON RELATIONSHIP.TO_NAME_ID = NAME_1.NAME_ID
WHERE  . . .;

您不应该需要SELECT DISTINCT。由于不必要的连接,你得到重复。