如何创建一个视图,排除与CASE语句中设置的任何条件不匹配的数据?

问题描述 投票:0回答:2

我正在尝试创建一个单独的视图,从另一个视图中获取数据并添加一列用于分类目的;但是,就像现在一样,我有很多记录在该附加列下具有NULL值...我想知道我是否可以管理以某种方式排除不符合在该列中设置的任何条件的记录CASE语句我用来改变视图?提前致谢

alter view2
select col1, case when col2='love' then 'non-shop'
when col2='choose' and col3='brand' then 'non-shop'
when col2='choose' and col3<>'brand' then 'shop'
when col2='buy' then 'shop'
end traffic_type
from view1
sql sql-server case sql-view
2个回答
1
投票

建立我的评论:

ALTER VIEW view2 as 

;WITH CTE AS
(
select col1, case when col2='love' then 'non-shop'
when col2='choose' and col3='brand' then 'non-shop'
when col2='choose' and col3<>'brand' then 'shop'
when col2='buy' then 'shop'
end as traffic_type
from view1
)
select * from CTE
where traffic_type is not null

正如@Larnu所说,我只是将orignal查询放在这里,而不是从view1链接


1
投票

我会做 :

alter view view2 as
    select col1, v11.traffic_type
    from view1 v1 cross apply
         ( values (case when (col2 = 'love') or (col2 = 'choose' and col3 = 'brand')
                        then 'non-shop'
                        when (col2 = 'choose' and col3 <> 'brand') or (col2 = 'buy')
                        then 'shop'
                   end)
         ) v11(traffic_type)
    where v11.traffic_type is not null;
© www.soinside.com 2019 - 2024. All rights reserved.