2

我有一组SQL Server包含调查信息的表,我想运行一个查询,每个调查有一行,每个答案有一个列。

结构设置如下:

ResponseHeader:
 ID (record for each survey)

Responses:
 ID 
 responseHeaderID
 questionID
 answerItemsID

AnswerItems:
 ID   (This is the value needed in each answer column)
 answerText

以下是我提出的查询:

SELECT  ResponseHeader.id
    ,   ResponseHeader.YOS
    ,   ResponseHeader.rankID
    ,   ResponseHeaderunitID
    ,   ResponseHeader.age
    ,   ResponseHeader.gender
    ,   MAX(CASE WHEN Responses.questionID = 42 THEN AnswerItems.id END)
    ,   MAX(CASE WHEN Responses.questionID = 43 THEN AnswerItems.id END)
    ,   MAX(CASE WHEN Responses.questionID = 44 THEN AnswerItems.id END)
    , --.....there are 79 of these lines in the query, one for each question (Responses.questionID)
        MAX(CASE WHEN Responses.questionID = 48 THEN AnswerItems.id END)
    ,   MAX(CASE WHEN Responses.questionID = 48 THEN AnswerItems.id END)
    ,   MAX(CASE WHEN Responses.questionID = 50 THEN AnswerItems.id END)
    ,   MAX(CASE WHEN Responses.questionID = 49 THEN AnswerItems.id END)
FROM ResponseHeader
LEFT OUTER JOIN Responses ON ResponseHeader.id = Responses.responseHeaderID
LEFT OUTER JOIN AnswerItems ON Responses.answerItemsID = AnswerItems.id
WHERE completed = 1
GROUP BY
        ResponseHeader.id
    ,   YOS
    ,   rankID
    ,   unitID
    ,   age
    ,   gender
ORDER BY ResponseHeader.id;

它确实返回了正确的结果集,但在查询分析器中执行需要 18 秒。它返回 4592 行,有 85 列。不幸的是,它达到了IIS缓冲区限制,因此在经典 ASP 页面中使用被认为是耗时的。增加缓冲区限制不是该作业的选项。我不确定如何以任何其他方式获取此信息。

我正在阅读有关枢轴查询的信息,但不理解它们。有没有办法使用这种方法或任何其他方法更快地获得我的结果?

4

1 回答 1

3

尝试这样的事情 -

DECLARE @Responses TABLE (responseHeaderID INT, questionID INT, answerItemsID INT)
DECLARE @ResponseHeader TABLE (id INT, YOS INT, rankID INT, unitID INT, age INT, gender CHAR(1), completed BIT)

SELECT * 
FROM (
    SELECT DISTINCT 
          rh.id
        , rh.YOS
        , rh.rankID
        , rh.unitID
        , rh.age
        , rh.gender
    FROM @ResponseHeader rh
    WHERE completed = 1
) rh
LEFT JOIN (
    SELECT *
    FROM (
        SELECT 
              r.responseHeaderID
            , r.questionID 
            , r.answerItemsID
        FROM @Responses r
    ) t
    PIVOT 
    (
        MAX(answerItemsID) FOR questionID IN ([42], [43], [44], [48], [50], [49])
    ) p
) t2 ON rh.id = t2.responseHeaderID
ORDER BY rh.id

输出 -

于 2013-09-02T05:16:51.013 回答