日期:2014-05-18 浏览次数:20504 次
--> 测试数据:[A1] if object_id('[A1]') is not null drop table [A1] create table [A1]([A01] varchar(1),[A02] varchar(6),[A03] varchar(8),[A04] datetime) insert [A1] select 'A','ZS0001',null,'20111201' union all select 'B',null,'ZS0002','20120201' union all select 'C','ZS0003','ZS0003','20120321' union all select 'D','ZS0004',null,'20120301' union all select 'E','ZS0005','ZS0005','20120301' select [A01] as [B01], case when [A02] is null then [A03] else [A02] end as [B02], LTRIM(YEAR([A04])) as [B03],ltrim(MONTH([A04])) as [B04] from A1 /* B01 B02 B03 B04 A ZS0001 2011 12 B ZS0002 2012 2 C ZS0003 2012 3 D ZS0004 2012 3 E ZS0005 2012 3 */
------解决方案--------------------
create table A(A01 varchar2(20),A02 varchar2(20),A03 varchar2(20),A04 date) insert into a values('A', 'ZS0001', null ,to_date('20111201','YYYYMMDD')) insert into a values('B', null , 'ZS0002' ,to_date('20120201','YYYYMMDD')) insert into a values('C', 'ZS0003', 'ZS0003' ,to_date('20120321','YYYYMMDD')) insert into a values('D', 'ZS0004', null ,to_date('20120301','YYYYMMDD')) insert into a values('E', 'ZS0005', 'ZS0005' ,to_date('20120301','YYYYMMDD')) create table B(B01 varchar2(20),B02 varchar2(20),B03 int,B04 int) insert into b values('A', 'ZS0001', 2011 ,12) insert into b values('B', 'ZS0002', 2012 ,2) insert into b values('C', 'ZS0003', 2012 ,3) insert into b values('D', 'ZS0004', 2012 ,3) insert into b values('E', 'ZS0005', 2012 ,3 ) select * from b --你是只比对月份则如下: select a.a01, (case when a.a02 = '' and a.a02 is null then a.a03 else a.a02 end) a02_03,to_char(a.a04,'yyyymmdd') a04, b.* from a , b where trunc(months_between(a.a04,to_date(to_char(b.b03) || LPAD(to_char(b.b04),2,'0') || '01','YYYYMMDD'))) = 1 /* A01 A02_03 A04 B01 B02 B03 B04 C ZS0003 20120321 B ZS0002 2012 2 D ZS0004 20120301 B ZS0002 2012 2 E ZS0005 20120301 B ZS0002 2012 2 3 rows selected. */ --不知道是否是a01-->b01 and a02(a03)-->b02 and 月份也相等,则如下: select a.a01, (case when a.a02 = '' and a.a02 is null then a.a03 else a.a02 end) a02_03,to_char(a.a04,'yyyymmdd') a04, b.* from a , b where a.a01 = b.b01 and (case when a.a02 = '' and a.a02 is null then a.a03 else a.a02 end) = b.b02 and trunc(months_between(a.a04,to_date(to_char(b.b03) || LPAD(to_char(b.b04),2,'0') || '01','YYYYMMDD'))) = 1 /* A01 A02_03 A04 B01 B02 B03 B04 no rows selected */ drop table a drop table b