在使用以下数据在 sql 中创建视图时需要帮助
Need help in creating a view in sql with following data
我正在处理的 table 包含以下格式的数据
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
using case and when 有帮助吗?
喜欢
case when A=1 then 'A'
when B=1 then 'B'
when C=1 then 'C'
else ''
end as type
提前致谢!
您可以使用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;
样本Table:
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
我们可以使用 union all 将 select 来自 table 的所有记录插入到视图中。下面的查询可以满足您的要求。谢谢你。
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));
我正在处理的 table 包含以下格式的数据
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
using case and when 有帮助吗? 喜欢
case when A=1 then 'A'
when B=1 then 'B'
when C=1 then 'C'
else ''
end as type
提前致谢!
您可以使用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;
样本Table:
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
我们可以使用 union all 将 select 来自 table 的所有记录插入到视图中。下面的查询可以满足您的要求。谢谢你。
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));