2015-01-22 2 views
0

다음과 같이 세 가지 쿼리가 있으며이를 하나로 결합해야합니다. 어떤 몸든지 그것을하는 방법을 아는가?여러 쿼리를 하나의 단일 쿼리로 결합하는 방법

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 

는 기본적으로,이 대답 질문입니다 :

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

다음 (한 전 사용) 테이블 열이다의 총 수를 찾으려면 이 테이블에 응답이 저장된 다른 사람들이 우리는 테이블 항목 위의 고려한다면

그래서 위의 3 조건에 따라 총 개수로 1을 받아야 즉 gender = 1 and Education = 4 and marital status = 2

누군가가 내가이 작업을 얻기 위해 무엇을해야하는지 말해 줄래?

+0

두 번째 질문 부분을 설명해주십시오. 또한 적절한 테이블 구조를 제공하십시오. –

+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 

우리는 얻을 행과 모든 조건에 따라 카운트가 각 행에 적용해야 할 수 있습니다.

+0

널 (NULL) 합계가 없기 때문에 'else 0'이 필요하지 않을 것이라고 확신합니다. 그렇지만 이것이 효과가 있습니다. – Bohemian

+0

오류 "데이터 형식을 nvarchar를 숫자로 변환하는 중 오류가 발생했습니다." 예를 들어 내 대답 열이 nvarchar이고 "sum (caseId = 2 및 ISNUMERIC (대답) = 1, 그 다음에 1 else 0 end)과 같은 쿼리를 FCount, "과 같이 수정하면 총 행 수가 줄어들지 않습니다. 내 where 절에 따른 정확한 수를 – Niha

+0

@MANOJ GOPI 내 질문을 수정했습니다. – Niha

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 
관련 문제