【问题标题】:Joining 3 tables to get Details from a Survey加入 3 个表格以从调查中获取详细信息
【发布时间】:2020-01-29 22:41:50
【问题描述】:

我进行了一项调查,其中有一些必须选择的领域。例如:工作场所、工作年限和满意度。

tlDetail
SurveyId QuestionId ChoiceId 
1          1           1
1          2           5
1          3           7
2          1           3
2          2           6
2          3           8

tblquestion
QuestionId Question
1           Question 1
2           Question 2
3           Question 3

TblChoice
ChoiceId QuestionId ChoiceName
1          1          HR
2          1          Accountant
3          1          Teacher
4          2          >10 years
5          2          <10 years
6          2          =10 years
7          3          satisfies
8          3          not satisfied
9          3          no comment

我需要编写一个查询,告诉我有多少教师 =10 年并且满意

【问题讨论】:

    标签: sql sql-server join count


    【解决方案1】:

    您可以使用两个级别的聚合:

    select count(*)
    from (
        select 1 x
        from tlDetail d
        inner join tblChoice c 
            on  c.QuestionId  = d.QuestionId 
            and c.ChoiceId = d.ChoiceId
        group by survey_id
        having
            max(case when c.ChoiceName = 'Teacher' then 1 end) = 1
            and max(case when c.ChoiceName = '=10 years' then 1 end) = 1
    ) t
    

    请注意,这假设两个不同的问题永远不会有相同的ChoiceName,这对您的示例数据来说很好,但在现实世界中不一定如此。如果您想要更准确的信息,那么您需要确定您期望哪个问题的答案是'Teacher''=10 years',例如:

    select count(*)
    from (
        select 1 x
        from tlDetail d
        inner join tblChoice c 
            on  c.QuestionId  = d.QuestionId 
            and c.ChoiceId = d.ChoiceId
        inner join tblQuestion q 
            on  q.QuestionId = d.QuestionId
        group by survey_id
        having
            max(case 
                when q.Question = 'Question 1' and c.ChoiceName = 'Teacher' 
                then 1 
            end) = 1
            and max(case 
                when q.Question = 'Question 2' and c.ChoiceName = '=10 years' 
                then 1 
            end) = 1
    ) t
    

    【讨论】:

    • 在select后面加上别名,否则会报错:“No column name was specified for column 1 of 't'。”
    猜你喜欢
    • 2012-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-08
    • 1970-01-01
    • 2022-08-19
    • 1970-01-01
    • 2020-11-22
    相关资源
    最近更新 更多