需要在两个联合查询中添加每个面试官完成的数量

时间:2011-07-18 20:41:39

标签: sql-server sql-server-2008

每个项目都有一个数据库。目前,我选择每位面试官,然后在调查中将结果相加以获得num_completes。我需要在多个项目中执行此操作,并添加每个面试的num_completes。到目前为止,这是我的代码:

SELECT interviewer AS INTERVIEWER, COUNT(completes) AS NUM_COMPLETES
    FROM tableone_projectone, interviewertable_mainsystemdb
    WHERE survey_result = '01' AND interviewertablekey=interviewernumber
    GROUP BY survey_result, interviewer
UNION ALL
 SELECT interviewer AS INTERVIEWER, COUNT(completes) AS NUM_COMPLETES
    FROM tableone_projecttwo, interviewertable_mainsystemdb
    WHERE survey_result = '01' AND interviewertablekey=interviewernumber
    GROUP BY survey_result, interviewer
    ORDER BY INTERVIEWER DESC
    GO

我不得不清理我的查询,如果它没有多大意义,那就很抱歉。

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

使用派生表:

SELECT INTERVIEWER, Sum(NUM_COMPLETES) 
FROM (...) AS unions 
GROUP BY INTERVIEWER

将所有工会放在......的位置上。

答案 1 :(得分:0)

@Lucent Fox基本上有正确的答案,但您还想记住将ORDER BY子句移动到查询外部。这将得到完整答案:

SELECT INTERVIEWER, Sum(NUM_COMPLETES) FROM (
    SELECT interviewer AS INTERVIEWER, COUNT(completes) AS NUM_COMPLETES
        FROM tableone_projectone, interviewertable_mainsystemdb
        WHERE survey_result = '01' AND interviewertablekey=interviewernumber
        GROUP BY survey_result, interviewer
    UNION ALL
    SELECT interviewer AS INTERVIEWER, COUNT(completes) AS NUM_COMPLETES
        FROM tableone_projecttwo, interviewertable_mainsystemdb
        WHERE survey_result = '01' AND interviewertablekey=interviewernumber
        GROUP BY survey_result, interviewer
) AS unions 
GROUP BY INTERVIEWER 
ORDER BY INTERVIEWER DESC