sql将一条记录分成2条记录

时间:2018-07-19 12:17:31

标签: sql sql-server

我有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     abc@xyz.com

我正在寻找以下数据-

id product_name start_date end_date
-----------------------------------    
123 Fiamma  1/01/1900   15/06/2017  
345 Fiamma  15/06/2017  31/12/2099

基本上,我想将表2数据分为2个记录,一个记录具有旧ID,该ID具有开始和结束日期,另一个记录具有新ID,具有起始和结束日期。

欢呼

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:0)

这是您可以运行的测试:

    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,'abc@xyz.com')


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

enter image description here