MSSQL:使用嵌套子查询的结果

时间:2017-09-28 15:24:44

标签: nested subquery

以下工作原理和输出结果如下图所示。

SELECT 
    SU_Internal_ID,
    NQ_QuestionText,
    NA_AnswerText,
    NoOfTimesChoosen 
FROM 
    (SELECT 
        U.SU_Internal_ID,
        NQ.NQ_QuestionText,
        NA.NA_AnswerText,
        COUNT(PC.UserID) AS NoOfTimesChoosen 
    FROM [dbo].[ParticipantNSChoices] PC 
    INNER JOIN [dbo].[KnowledgeSurveyAnswers] NA 
        on PC.NA_Internal_ID = NA.NA_Internal_ID 
    INNER JOIN [dbo].[KnowledgeSurveyQuestions] NQ 
        on PC.NQ_Internal_ID = NQ.NQ_Internal_ID 
    INNER JOIN [dbo].[AspNetUsers] U 
        on PC.UserID = U.Id 
    WHERE 
        U.SU_Internal_ID=1 
        and NQ.NQ_QuestionText LIKE '%Do you feel comfortable working with computers%' 
    GROUP 
        BY U.SU_Internal_ID,
        NQ.NQ_QuestionText,
        NA.NA_AnswerText ) as A

我想添加一列来显示两个答案的百分比'否'并且'是':旁边的'否'我想要' 20'并且旁边是'是' ' 80',但我在这方面很新,而且被卡住了;我将不胜感激任何帮助。感谢。

Result of working script

1 个答案:

答案 0 :(得分:0)

你不需要外部的SELECT。

SELECT 
    U.SU_Internal_ID,
    NQ.NQ_QuestionText,
    NA.NA_AnswerText,
    COUNT(PC.UserID) AS NoOfTimesChoosen,
    (cast(COUNT(PC.UserID) as float) / 
        cast(
            (select count(*) from [dbo].[ParticipantNSChoices] PC2 
                INNER JOIN [dbo].[KnowledgeSurveyAnswers] NA2 on PC2.NA_Internal_ID = NA2.NA_Internal_ID 
                INNER JOIN [dbo].[KnowledgeSurveyQuestions] NQ2 on PC2.NQ_Internal_ID = NQ2.NQ_Internal_ID 
                INNER JOIN [dbo].[AspNetUsers] U2 on PC2.UserID = U2.Id 
                WHERE 
                    U2.SU_Internal_ID=1 
                    and NQ2.NQ_QuestionText LIKE '%Do you feel comfortable working with computers%' ) 
            as float)) 
            * 100 as PercentChosen
FROM [dbo].[ParticipantNSChoices] PC 
INNER JOIN [dbo].[KnowledgeSurveyAnswers] NA 
    on PC.NA_Internal_ID = NA.NA_Internal_ID 
INNER JOIN [dbo].[KnowledgeSurveyQuestions] NQ 
    on PC.NQ_Internal_ID = NQ.NQ_Internal_ID 
INNER JOIN [dbo].[AspNetUsers] U 
    on PC.UserID = U.Id 
WHERE 
    U.SU_Internal_ID=1 
    and NQ.NQ_QuestionText LIKE '%Do you feel comfortable working with computers%' 
GROUP 
    BY U.SU_Internal_ID,
    NQ.NQ_QuestionText,
    NA.NA_AnswerText

counts将为integers,因此您需要cast作为floats才能进行分割。然后,您可以根据自己的喜好进一步格式化。此外,我可能没有您的确切分母,因为我不知道您的数据是什么样的,但您可以修改以匹配您需要的数据。