用过滤器分组

时间:2019-08-30 08:20:29

标签: sql sql-server group-by

我有以下三个表:

CREATE TABLE [dbo].[SurveyComments](
[Id] [int] IDENTITY(1,1) NOT NULL,
[QuestionNumber] [int] NOT NULL,
[Comment] [varchar](250) NULL,
[FIleName] [nchar](50) NULL)

CREATE TABLE [dbo].[SurveyQuestions](
[Id] [int] IDENTITY(1,1) NOT NULL,
[QuestionNumber] [int] NOT NULL,
[Description] [varchar](250) NULL)

CREATE TABLE [dbo].[SurveyResponses](
[Id] [int] NOT NULL,
[SurveyQuestionNumber] [int] NOT NULL,
[Answer1] [bit] NULL,
[Answer2] [bit] NULL,
[Answer3] [bit] NULL,
[Answer4] [bit] NULL,
[Answer5] [bit] NULL,
[Answer6] [bit] NULL,
[FileName] [nchar](50) NULL)

我希望列出问卷集(文件名)包括问题43的答案1的那些问题和答案。

   SELECT SurveyQuestionNumber
    , SurveyQuestions.Description
    , COUNT(CASE WHEN Answer1 = 1 THEN 1 END) 'Answer 1'
    , COUNT(CASE WHEN Answer2 = 1 THEN 1 END) 'Answer 2'
    , COUNT(CASE WHEN Answer3 = 1 THEN 1 END) 'Answer 3'
    , COUNT(CASE WHEN Answer4 = 1 THEN 1 END) 'Answer 4'
    , COUNT(CASE WHEN Answer5 = 1 THEN 1 END) 'Answer 5'
    , COUNT(CASE WHEN Answer6 = 1 THEN 1 END) 'Answer 6'
    FROM [StaffSurveyQuestionnaire_2019].[dbo].[SurveyResponses]
    JOIN SurveyQuestions on SurveyResponses.SurveyQuestionNumber = SurveyQuestions.QuestionNumber
    GROUP BY SurveyQuestionNumber, Description
    order by SurveyQuestionNumber asc

这使我可以分组并计算所有答案。此查询的样本数据

enter image description here

我尝试了having count(case when QuestNumber = 53 then 1 end) > 0,但是对于where子句中指定的问题,它只返回一行,但是我希望列出所有带有答案计数的问题,例如,在所有调查表集中,其中有人对Q53回答1 = 1。因此,这将列出所有Q1-Q60的答案计数,仅针对Q53被回答为Answer1 = 1

的集合。

2 个答案:

答案 0 :(得分:2)

  

我希望列出其中的所有问题和答案。   问卷集(文件名)包括问题43的答案1。

您可能需要一个WHERE FileName IN (...)条件,也可以写成WHERE EXISTS (...)

FROM SurveyResponses
JOIN SurveyQuestions ON SurveyResponses.SurveyQuestionNumber = SurveyQuestions.QuestionNumber
WHERE EXISTS (
    SELECT 1
    FROM SurveyResponses AS q43a1
    WHERE q43a1.QuestionNumber = 43
    AND q43a1.Answer1 = 1
    AND q43a1.FileName = SurveyResponses.FileName
)
GROUP BY SurveyQuestionNumber, Description

答案 1 :(得分:1)

将此添加到查询中

    WHERE [FileName] IN (SELECT [FileName] FROM [StaffSurveyQuestionnaire_2019].[dbo].[SurveyResponses]
                        WHERE SurveyQuestionNumber=43 and Answer1=1)