带有字符串连接的SQL Server数据透视表

时间:2016-12-02 11:46:26

标签: sql-server pivot concatenation

我有以下数据

| Name      | Subject   | Answer                |
|:----------|:----------|:---------------------:|
|Pranesh    |Physics    |Numerical Problems     |
|Pranesh    |Physics    |Other                  |
|Pranesh    |Chemistry  |Understanding Concepts |
|Pranesh    |Chemistry  |Organic chemistry reactions
|Pranesh    |Maths      |Lack of understanding  |
|Pranesh    |Maths      |Insufficient practice  |
|Pranesh    |Maths      |Other                  |

使用此SQL查询:

select * 
from 
    (select  
         l.FullName Name, sq.Title Subject, cAns.Name Answer 
     from 
         Answer as sa
     left join
         Question AS sq on sq.ID = sa.QuestionID
     left join 
         Master as cAns on cAns.ID = sa.AnswerID
     left join 
         Profile as l on l.ID = sa.ProfileID) src
pivot
    (max(Answer)
        for Subject in ([Physics], [Chemistry], [Maths], [Biology],[ComputerScience], [CommonUnderstanding])) piv;

我能够获得如下数据

enter image description here

如何连接同一主题的答案栏并在上面的屏幕截图中显示相同的内容?

2 个答案:

答案 0 :(得分:1)

我已经根据名称和主题连接了答案列表,然后应用了旋转 -

declare @temp table (name varchar(100), subject varchar(100), answer varchar(100))

insert into @temp
            select 'Pranesh','Physics'  ,'Numerical Problems'
union all   select 'Pranesh','Physics'  ,'Other'
union all   select 'Pranesh','Chemistry','Understanding Concepts'
union all   select 'Pranesh','Chemistry','Organic chemistry reactions'
union all   select 'Pranesh','Maths'    ,'Lack of understanding'
union all   select 'Pranesh','Maths'    ,'Insufficient practice'
union all   select 'Pranesh','Maths'    ,'Other'
union all   select 'Ramesh','Biology'   ,   'Other'
union all   select 'Ramesh','Biology'   ,   'Science'

;with cte as (select distinct name, subject from @temp)
select * from
(
    select
        c.name,
        c.subject,
        answer = stuff((select ',' + answer from @temp t where t.name=c.name and t.subject=c.subject for xml path('')), 1, 1, '')
    from cte c
) src
pivot
(
    max(answer) for subject in ([Physics], [Chemistry], [Maths], [Biology],[ComputerScience],[CommonUnderstanding])
) piv

答案 1 :(得分:0)

试试这个: -

SELECT ANS, PHYSICS,CHEMISTRY,MATHS
FROM
(
SELECT  L.FULLNAME NAME, SQ.TITLE SUBJECT, CANS.NAME ANSWER FROM ANSWER AS SA
LEFT JOIN QUESTION AS SQ ON SQ.ID = SA.QUESTIONID
LEFT JOIN MASTER AS CANS ON CANS.ID = SA.ANSWERID
LEFT JOIN PROFILE AS L ON L.ID = SA.PROFILEID
) AS T
UNPIVOT
(
  COMBINE_COLUMN_VALUES FOR ANS IN (ANSWER)
) AS U
PIVOT
(
  MAX(COMBINE_COLUMN_VALUES) FOR [SUBJECT] IN (PHYSICS,CHEMISTRY,MATHS)
) AS P