我有三个查询,我需要将它们合并为一个。有没有人知道怎么做?
select COUNT(*) from dbo.VWAnswer where questionId =2 and answer =1
select COUNT(*) from dbo.VWAnswer where questionId =3 and answer =4
select COUNT(*) from dbo.VWAnswer where questionId =5 and answer =2
我想了解那些gender = 1 and Education = 4 and marital status = 2
以下是我所指的表格列(有一个例子):
questionId questionText anwser AnserSheetID
1 Gender 1 1
2 Qualification 4 1
3 Marital Status 2 1
1 Gender 2 2
2 Qualification 1 2
3 Marital Status 2 2
1 Gender 1 3
2 Qualification 3 3
3 Marital Status 1 3
基本上,这些问题由不同的人回答,他们的答案存储在此表中。
因此,如果我们考虑上面的表项,我应该根据上述3个条件获得1作为总计数,即gender = 1 and Education = 4 and marital status = 2
有人可以告诉我我需要做些什么才能让它发挥作用吗?
答案 0 :(得分:2)
如果要组合三个计数查询,可以尝试使用以下SQL来完成它。
select
sum(case when questionId =2 and anwser=1 then 1 else 0 end) as FCount,
sum(case when questionId =3 and anwser=4 then 1 else 0 end) as SCount,
sum(case when questionId =5 and anwser=2 then 1 else 0 end) as TCount
from dbo.VWAnswer
更新1:
select
Sum(case when questionText='Gender' and anwser='1' then 1 else 0 end) as GenderCount,
Sum(case when questionText='Qualification' and anwser='4' then 1 else 0 end) as EducationCount,
Sum(case when questionText='Marital Status' and anwser='2' then 1 else 0 end) as MaritalCount
from VWAnswer
我们只能根据行获取计数,每个条件应适用于每一行。
答案 1 :(得分:0)
您可以使用符合条件的联合视图,并选择适合您条件的行数。
Select COUNT(*) as cnt from
(
Select a.AnserSheetID
from VWAnswer a
Join VWAnswer b on a.AnserSheetID=b.AnserSheetID and b.questionId = 2 and b.anwser=4
Join VWAnswer c on a.AnserSheetID=c.AnserSheetID and c.questionId = 3 and c.anwser=2
where a.questionId=1 and a.anwser=1
) hlp