6

How to insert record from Table A to Table B based on the conditions in Table C.

Table A:

ID  Name   DateFrom   DateTo
1   Alex   22-7-2015  26-7-2015
2   Alice  21-8-2015  25-8-2015

Table C:

ID  Quarter   DateFrom   DateTo
1   Quater 1  1-7-2015  31-7-2015
2   Quater 2  1-8-2015  31-8-2015

If the records from Table A is between the date range in Table C. It will insert into a new Table B.

Redemption is Table B

insert into redemption(staffID,staffName,department,pointsAccumulated,referrerID) 
select referrerStaffID,referrerName,referrerDepartment,SUM(points),activeDirectoryID 
FROM referral 
WHERE NOT EXISTS (select * from redemption1 where referrerID=activeDirectoryID) group by activeDirectoryID;
Salman A
  • 262,204
  • 82
  • 430
  • 521
Lee Lee
  • 63
  • 3
  • Can you please share the structure of table b and the records you want inserted for this sample data? Thanks! – Mureinik Jul 28 '15 at 06:38

4 Answers4

3

Try this

Insert into tableB(Id,name,datefrom,dateto)
select t1.Id,t1.name,t1.datefrom,t1.dateto from tableA as t1 
inner join tableC as t2 on t1.id=t2.id 
where 
t1.datefrom between t2.datefrom and t2.dateto or 
t1.dateto between t2.datefrom and t2.dateto
Madhivanan
  • 13,470
  • 1
  • 24
  • 29
1

I would use a correlated subquery with WHERE NOT EXISTS.. construct

insert into 
redemption(
            staffID,
            staffName,
            department,
            pointsAccumulated,
            referrerID
          ) 
select 
referrerStaffID,
referrerName,
referrerDepartment,
SUM(points),
activeDirectoryID 
FROM referral  r
WHERE NOT EXISTS (
                    select 1 from redemption1 r1 where 
                    r1.referrerID=r1.activeDirectoryID 
                    and (r.datefrom between r1.datefrom and r1.dateto or 
                         r.dateto between r1.datefrom and r1.dateto) 
                 )
group by r.referrerStaffID,r.referrerName,r.referrerDepartment,r.activeDirectoryID;
SouravA
  • 5,147
  • 2
  • 24
  • 49
1

You can use the below query

insert into tableB(id,name,datefrom,dateto)
select A.id,A.name,A.datefrom,A.dateto from tableA A join tableC C 
                       on A.id=C.id 
      where TO_DATE(A.datefrom,'DD-mm-yyyy') 
            between TO_DATE(C.datefrom,'DD-mm-yyyy') and TO_DATE(c.dateto,'DD-mm-yyyy')
      and TO_DATE(A.dateto,'DD-mm-yyyy') 
            between TO_DATE(C.datefrom,'DD-mm-yyyy') and TO_DATE(c.dateto,'DD-mm-yyyy')

Please check the answer here SQL Fiddle

Arun Palanisamy
  • 5,281
  • 6
  • 28
  • 53
1

I think this is already answered by everyone else, but I'd just like to add if the schema for table A and table B are the same you can also do something like:

Insert into tableB 
Select * from tableA
Where....

Not repeating where clause since its already answered.

Polynomial Proton
  • 5,020
  • 20
  • 37