Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

Help in Writing a query - Tried but unable to put logic together

$
0
0

Hi, Before I ask for this help, I tried with Merge but couldn't get what I needed.

so seeking some help in writing a query to move data  from source table to Target table. Query below is for sample data.

Based on the data, I should either

1) Insert the source record as-is

2) Update Target table record(some times update multiple Column values in Target Table)

3) Ignore the Source record

CREATE TABLE Target
(
ID INT Identity(1,1),
DeviceID Varchar(10),
UserID Varchar(10),
Startdate Date,
EndDate Date Default NULL,

primary key (DeviceID,UserID,Startdate)

)

INSERT INTO Target
VALUES ('D1', 'U1', '2013-11-01','2013-11-15')
INSERT INTO Target
VALUES ('D1', 'U2', '2013-11-16','2013-11-25')
INSERT INTO Target
VALUES ('D1', 'U3', '2013-11-26',null)

CREATE TABLE Source
(
DeviceID Varchar(10),
UserID Varchar(10),
Startdate Date,
Enddate Date
)

INSERT INTO Source
VALUES ('D1', 'U4', '2013-11-16',NULL)
INSERT INTO Source
VALUES ('D1', 'U3', '2013-11-29',NULL)
INSERT INTO Source
VALUES ('D1', 'U3', '2013-11-24',NULL)
INSERT INTO Source
VALUES ('D2', 'U5', '2013-11-28',NULL)
INSERT INTO Source
VALUES ('D1', 'U5', '2013-11-28',NULL)
INSERT INTO Source
VALUES ('D1', 'U6', '2013-11-20',NULL)
INSERT INTO Source
VALUES ('D1',    'U7',    '2013-11-01',NULL)
INSERT INTO Source
VALUES ('D1',    'U3',    '2013-11-30',NULL)
INSERT INTO Source
VALUES ('D1',    'U2',    '2013-11-10',NULL)
INSERT INTO Source
VALUES ('D4',    'U7',    '2013-12-12',NULL)
INSERT INTO Source
VALUES ('D4',    'U8',    '2013-12-15',NULL)
INSERT INTO Source
VALUES ('D2',    'U5',    '2013-11-27',NULL)
INSERT INTO Source
VALUES ('D1',    'U5',    '2013-12-12',NULL)

Few Points to remember:

1    DeviceID, UserID and StartDate is Primary Key
2    End Date is user generated. It is always start date - 1. Enddate should always be greater than or equal to Startdate.
3    Only one user can have a device on given day
4    If a device and startdate combination already exists in the Target Table, we should not insert the source record in destination
5    If User one is using Device1, it will be under him untill next user uses it. Meaning, if a new record with higher start date comes in the source table, we should not insert that record in destination table.

Conditions to Insert or Update or Ignore the source record: BELOW is the sample data and what I am expecting .. Sorry, post is too long to better explain what I am looking for.

Thanks for your time and Thanks in Advance

Ram



Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>