我有2个表格,数据如下表1-
id name id_start_date
---------------------
345 Fiamma 1/01/1900
表2-
Change_Date Old_id New_id Users
-------------------------------
15/06/2017 123 345 [email protected]
我正在寻找以下数据 -
id product_name start_date end_date
-----------------------------------
123 Fiamma 1/01/1900 15/06/2017
345 Fiamma 15/06/2017 31/12/2099
基本上我想将表2数据分成两个记录,一个具有旧id,该id的开始和结束日期,另一个具有开始和结束日期的新id。
干杯
select t2.old_id as id, t1.name as product_name, t1.start_date, t2.change_date as end_date
from table1 t1
INNER JOIN table2 t2 ON t1.id = t2.new_id
UNION
select t1.id as id, t1.name as product_name, t2.change_date, "" as end_date
from table1 t1
INNER JOIN table2 t2 ON t1.id = t2.new_id
这是一个可以运行的测试:
create table #table1
(
id int,
name varchar(50),
start_date datetime
)
GO
create table #table2
(
change_date datetime,
Old_id int,
New_id int,
users varchar(50)
)
GO
insert into #table1
values (345,'Fiamma','01/01/1900')
insert into #table2
values ('15/06/2017',123,345,'[email protected]')
select * from #table1
select * from #table2
select t2.old_id as id, t1.name as product_name, t1.start_date as start_date, t2.change_date as end_date
from #table1 t1
INNER JOIN #table2 t2 ON t1.id = t2.new_id
UNION
select t1.id as id, t1.name as product_name, t2.change_date as start_date , DATEADD(YEAR,+10,GETDATE()) as end_date
from #table1 t1
INNER JOIN #table2 t2 ON t1.id = t2.new_id
drop table #table1
drop table #table2