2017-01-02 3 views
-1
와 SQL에서 뷰를 작성하는 데 도움이 필요

내가 작업하고있는 테이블을 사용하는 것이다 나는이는 다음과 같은 데이터

Name | Type 
abc | A 
abc | C 
xyz | B 
xyz | C 
pqr | C 

처럼보기 a를 만드는 데 필요한 형식을

Name | A | B | C 
---------------- 
abc | 1 | 0 | 1 
xyz | 0 | 1 | 1 
pqr | 0 | 0 | 1 

다음의 데이터를 포함 도움이 될 때가 언제입니까? 은

case when A=1 then 'A' 
    when B=1 then 'B' 
    when C=1 then 'C' 
    else '' 
    end as type 

감사합니다.

+0

! 그것은 나를 위해 일했다! 나는 충분한 평판이 없기 때문에 나는 upvote 할 수 없다. – mohan111

+0

감사 ..do 대답의 당신을 도와줍니다 asked..if 그래서 당신은 당신이 가지고있는 질문에 뭔가를 응답해야 당으로

create or replace view test1 as ( select name,field from ( select name,'A' as field from test where a = 1 union all select name,'B' as field from test where b = 1 union all select name,'C' as field from test where c = 1)); 

답변

1

샘플 테이블 :

DECLARE @Table1 TABLE 
    (Name varchar(3), A int, B int, C int) 
; 

INSERT INTO @Table1 
    (Name, A, B, C) 
VALUES 
    ('abc', 1, 0, 1), 
    ('xyz', 0, 1, 1), 
    ('pqr', 0, 0, 1) 
; 

스크립트

Select Name,[Type] from (
select Name,CASE WHEN VAL = 1 then COL ELSE NULL END Type,VAL from @Table1 
CROSS APPLY(VALUES('A',A),('B',B),('C',C))CS(COL,VAL) 
)T WHERE T.Type IS NOT NULL 
0

당신은 사용할 수 있습니다 union all

select name,'A' from t where a = 1 union all 
select name,'B' from t where b = 1 union all 
select name,'C' from t where c = 1; 

당신은 또한 그룹 상태 등 :

select name, col 
from 
    (select name, 'A' col, a val from t union all 
    select name, 'B', b from t union all 
    select name, 'C', c from t) 
where val = 1; 
0

union all을 사용하여 테이블의 모든 레코드를 선택하고 뷰에 삽입 할 수 있습니다. 아래 쿼리를 사용하면 요구 사항을 충족 할 수 있습니다. 고맙습니다.

는 upvote에 ..happy 코딩