如何从现有列创建新列?

时间:2014-09-09 15:32:49

标签: sql teradata

在表AZ中我有3列说a,b,c ||这里c是d ||的别名如何在同一个表中创建一个新列说" e"来自专栏c

select 
    a.lyl_id_no,
    sum(a.trn_tot_prc) as PURCH,
    sum(case when a.trn_dt > current_date - 365 then 1 else 0 end) cnt_trips_1yr , 
from abc a
group by 1

结果:

a.lylid   purch  cnt_trips_lyr
123        12          4
242        10         1

但是我需要在同一个表格中使用新列,它应该说cnt_trips_1yr> 3,cnt_trips_1yr> 2

1 个答案:

答案 0 :(得分:0)

如果我理解正确,只需添加更多条件。我认为最简单的方法是使用子查询:

select a.*,
       (case when cnt_trips_1yr > 3 then 1 else 0 end) as IsCntGt3,
       (case when cnt_trips_1yr > 2 then 1 else 0 end) as IsCntGt2
from (select a.lyl_id_no,
             sum(a.trn_tot_prc) as PURCH,
             sum(case when a.trn_dt > current_date - 365 then 1 else 0 end) as cnt_trips_1yr
      from abc a
      group by a.lyl_id_no
     ) a;