如何将同一个表的两个不同计数加在一起?

时间:2015-07-21 18:55:51

标签: sql sql-server sql-server-2008

我正在处理的表格是对一定数量问题的答案记录。我想找出人们说的百分比,是的,绝对是'关于提供者23的问题470,477,479,481,483。所以我试着计算答案的总数和“是的,绝对是'答案。我可以单独完成它们,但无法在一个表中加入它们。

一个查询是获取表SurveyAnswerFact中记录的总计数。

SELECT SurveyQuestionKey, count(1)
FROM [WAREHOUSE].[dbo].[SurveyAnswerFact]
WHERE ([ProviderKey] = 23) 
AND ([SurveyQuestionKey] IN (470,477,479,481,483))        
AND ([Response] = 'Yes, definitely') 
AND ([ResponseDateKey] BETWEEN 20140601 AND 20150531)
GROUP BY SurveyQuestionKey

结果:

470   44
477   40
479   43
481   43
483   44

另一个问题是得到答案的数量是,是的,绝对是'

SELECT SurveyQuestionKey, count(1)
FROM [WAREHOUSE].[dbo].[SurveyAnswerFact]
WHERE (ProviderKey = 23) 
AND (SurveyQuestionKey IN (470,477,479,481,483)) 
AND ([ResponseDateKey] BETWEEN 20140601 AND 20150531)
GROUP BY SurveyQuestionKey

结果:

470   43
477   39
479   35
481   42
483   39

我尝试使用SQL将它们连接在一起,但结果与第一个查询的结果相同。我的预期结果是这样的:

470   43   44
477   39   40
479   35   43
481   42   43
483   39   44

有人能教会我加入他们的正确方法吗?

2 个答案:

答案 0 :(得分:0)

也许你的意思是......

我所做的就是消除响应中的where子句,并将其添加到select和group by。

 SELECT SurveyQuestionKey, Response, count(1)
    FROM [WAREHOUSE].[dbo].[SurveyAnswerFact]
    WHERE ([ProviderKey] = 23) 
      AND ([SurveyQuestionKey] IN (470,477,479,481,483))        
      AND ([ResponseDateKey] BETWEEN 20140601 AND 20150531)
   GROUP BY SurveyQuestionKey, Response

--------------基于新信息的更新---------

有几种方法可以做到这一点。使用案例陈述

SELECT SurveyQuestionKey, count(1) as Totalcount, sum(case when Response = 'Yes, definitely' then 1 else 0 end) as [Yes Def]
FROM [WAREHOUSE].[dbo].[SurveyAnswerFact]
WHERE ([ProviderKey] = 23) 
AND ([SurveyQuestionKey] IN (470,477,479,481,483))        
AND ([ResponseDateKey] BETWEEN 20140601 AND 20150531)
GROUP BY SurveyQuestionKey

另一种方法是按照您的建议加入表,但这会产生更多开销。 (这为每个查询使用一个公用表,使连接更容易阅读。)

With totalCount as (SELECT SurveyQuestionKey, count(1) cnt
FROM [WAREHOUSE].[dbo].[SurveyAnswerFact]
WHERE ([ProviderKey] = 23) 
AND ([SurveyQuestionKey] IN (470,477,479,481,483))        
AND ([Response] = 'Yes, definitely') 
AND ([ResponseDateKey] BETWEEN 20140601 AND 20150531)
GROUP BY SurveyQuestionKey),

YesDefCount as (SELECT SurveyQuestionKey, count(1) cnt
FROM [WAREHOUSE].[dbo].[SurveyAnswerFact]
WHERE ([ProviderKey] = 23) 
AND ([SurveyQuestionKey] IN (470,477,479,481,483))        
AND ([ResponseDateKey] BETWEEN 20140601 AND 20150531)
GROUP BY SurveyQuestionKey)

SELECT surveyQuestionKey, totalcount.cnt, yesDefCount.count
from totalcount A
LEFT JOIN YESDEFCOUNT B 
 on A.SurveyQuestionKey = B.SurveyQuestionKey;

答案 1 :(得分:0)

SELECT SurveyQuestionKey, count(1), x.totals
  FROM [WAREHOUSE].[dbo].[SurveyAnswerFact], 
       (select count(1) totals from [WAREHOUSE].[dbo].[SurveyAnswerFact]) x
 WHERE ([ProviderKey] = 23) 
   AND ([SurveyQuestionKey] IN (470,477,479,481,483))        
   AND ([Response] = 'Yes, definitely') 
   AND ([ResponseDateKey] BETWEEN 20140601 AND 20150531)
 GROUP BY SurveyQuestionKey