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

SQL-Update using above rows

$
0
0








/*Hi Experts 
I am working on SQL 2012 ,

I have a table example "TEMP1" where Record of single Person comes multiple Time ,Based on there SourceID.
I need to Insert This Data into another Table example "TEMP2"which have same Structure 


REQUIREMENT: I need Only One Record of a Person Where SourceID is MINIMUM.
Example 
if Person "x" is considered the it should take the Record where SourceID=1 (MIN source ID for Person "x")
Location=NEWYORK because it is already Present for Min Source Id
SNO will be 22 because sno is NUll for SourceID 1 so it Picks where SourceID=2
IOCDE will be 333  because IOCDE  is NUll for SourceID 1 and SourceID2 so it Picks where SourceID=3
*/

/*below is my Source Table */
CREATE TABLE TEMP1 (NAME NVARCHAR(100),LOCATION NVARCHAR(100),SNO INT ,ICODE INT ,SOURCEID INT ,SURROGATE_KEY INT)
INSERT INTO TEMP1
SELECT 'X','NEWYORK','',333,3,1001 UNION ALL
SELECT 'X','NEWYORK','','',1,1002 UNION ALL
SELECT 'X','NEWYORK',22,'',2 ,1003 UNION ALL

SELECT 'Y','LONDON','','',3,1004 UNION ALL
SELECT 'Y','',44,'',1 ,1005 UNION ALL
SELECT 'Y','',22,'',2 ,1006 UNION ALL
SELECT 'Y','','',444,4 ,1007 UNION ALL

SELECT 'Z','',22,'',4 ,1008 UNION ALL
SELECT 'Z','','',55,2 ,1009  UNION ALL

SELECT 'A','AUSTRALIA',999,55,2,1010 UNION ALL
SELECT 'B','',999,'',2 ,1011 UNION ALL
SELECT 'B','INDIA',999,500,3,1012 UNION ALL
SELECT 'B','CHINA',999,600,4 ,1013

SELECT * FROM TEMP1


/*below is my new Target Table which I need to Populate using Above source Table  */

CREATE TABLE TEMP2 (NAME NVARCHAR(100),LOCATION NVARCHAR(100),SNO INT ,ICODE INT ,SOURCEID INT ,SURROGATE_KEY INT)
INSERT INTO TEMP2

SELECT 'X','NEWYORK',22,333,1,1002 UNION ALL
SELECT 'Y','LONDON',44,444,1,1005 UNION ALL
SELECT 'Z','',22,55,2,1009 UNION ALL
SELECT 'A','AUSTRALIA',999,55,2,1010 UNION ALL
SELECT 'B','INDIA',999,500,2 ,1011

select * from TEMP2


/Sorry Experts ,I missed to add a surrogate Key in the Table ,Every Rows has Surrogate Key and single Record that comes should have
Surrogate Key available in MINIMUM sourceID /












Viewing all articles
Browse latest Browse all 23857

Trending Articles



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