需要帮助在sql中使用以下数据创建视图

时间:2017-01-02 06:35:11

标签: sql views case

我正在处理的表包含以下格式的数据

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

我需要创建一个像这样的视图

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

请问用例和何时有用? 像

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

提前致谢!

3 个答案:

答案 0 :(得分: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 

答案 1 :(得分: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;

您还可以将where条件分组为:

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;

答案 2 :(得分:0)

我们可以使用union all从表中选择所有记录并插入到视图中。以下查询足以满足您的要求。谢谢。

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));