如何在Pivot中编写动态列创建Select语句中的Where条件

时间:2014-12-03 07:26:22

标签: .net pivot

这里如何在此处写出Where条件我只想选择特定的考试ID位置 下面提到

DECLARE @cols NVARCHAR(2000);
    SELECT  @cols = STUFF(( SELECT DISTINCT TOP 100 PERCENT
                                    '],[' + t2.PartID
                            FROM    StudentAnswer AS t2
                            ORDER BY '],[' + t2.PartID
                            FOR XML PATH('')
                          ), 1, 2, '') + ']'

    DECLARE @Query NVARCHAR(4000);
    SET @Query= N' SELECT ExamID,StudentID,'+@cols+'
    FROM 
    (SELECT   StudentID,PartID,ExamID
                      , CASE WHEN Ans=CorrectAns THEN 1 WHEN Ans!=CorrectAns THEN 0 END as Result
              FROM StudentAnswer  **//Where Condtion**
            ) p 
             PIVOT ( SUM(Result)
                        FOR PartID 
                          IN ('+@cols+')
                      )  AS pvt;'
    EXECUTE(@Query);

2 个答案:

答案 0 :(得分:0)

只是做它........

DECLARE @cols NVARCHAR(2000);
SELECT  @cols = STUFF(( SELECT DISTINCT TOP 100 PERCENT
                                '],[' + t2.PartID
                        FROM    StudentAnswer AS t2
                        ORDER BY '],[' + t2.PartID
                        FOR XML PATH('')
                      ), 1, 2, '') + ']'

DECLARE @Query NVARCHAR(4000);
SET @Query= N' SELECT ExamID,StudentID,'+@cols+'
FROM 
(SELECT   StudentID,PartID,ExamID
                  , CASE WHEN Ans=CorrectAns THEN 1 WHEN Ans!=CorrectAns THEN 0 END as Result
          FROM StudentAnswer  Where ExamID = yourExamID
        ) p 
         PIVOT ( SUM(Result)
                    FOR PartID 
                      IN ('+@cols+')
                  )  AS pvt;'
EXECUTE(@Query);

如果您有任何问题,请提及您的问题以及输出的更多细节......

答案 1 :(得分:0)

我用这个答案得到答案。

DECLARE @cols NVARCHAR(2000);
    SELECT  @cols = STUFF(( SELECT DISTINCT TOP 100 PERCENT
                                    '],[' + t2.PartID
                            FROM    StudentAnswer AS t2
                            ORDER BY '],[' + t2.PartID
                            FOR XML PATH('')
                          ), 1, 2, '') + ']'

    DECLARE @Query NVARCHAR(4000);
    SET @Query= N' SELECT ExamID,StudentID,'+@cols+'
    FROM 
    (SELECT   StudentID,PartID,ExamID
                      , CASE WHEN Ans=CorrectAns THEN 1 WHEN Ans!=CorrectAns THEN 0 END as Result
              FROM StudentAnswer WHERE ExamID=''EX201411E1''**// Here Use the tow single Qutation**``
            ) p 
             PIVOT ( SUM(Result)
                        FOR PartID 
                          IN ('+@cols+')
                      )AS pvt;'                    
    EXECUTE(@Query);