简体   繁体   中英

Copy specific data from one table to another in sql

I have two tables, one is CurrentReport and other is Challan table, and another is current report table that are showing in table. I copy the value of following column of currentReport table

 [Title],
    [ISBN],
    [Author1],
    [FinalStatus],
    [MssType] 

but now I want to copy stepno of challan table having min date into work1 of currentreport table in both tables refrence no. are same. In challan table there is multiple enteries in challan table having same reference no among which I want to get stepno having min date.

Columns in challan tables are

       [ChallanNo]
      ,[ReferenceNo]
      ,[PersonID]
      ,[PersonCategory]
      ,[ChallanDate]
      ,[PreparedBy]
      ,[CreatedOn]
      ,[Publisher]
      ,[TemplateName]
      ,[TemplateSubject]
      ,[TemplateBody]
      ,[EmailAttachment]
      ,[PreviousProjectedDate]
      ,[PreviousReminderDate]
      ,[PreviousActionDate]
      ,[NextProjectedDate]
      ,[NextReminderDate]
      ,[NextActionDate]
      ,[ReminderText]
      ,[ReceivedDate]
      ,[StepNo]
      ,[ChallanStatus]
      ,[IsActive]
      ,[IsReceived] 

Columns in CurrentReport table are:

 [ReferenceNo]
          ,[Title]
          ,[ISBN]
          ,[Author1]
          ,[FinalStatus]
          ,[MssType]
          ,[Work1]
          ,[GivenTo1]
          ,[ChallanDate1]
          ,[ReceivedDate1]
          ,[Work2]
          ,[GivenTo2]
          ,[ChallanDate2]
          ,[ReceivedDate2]
          ,[Work3]
          ,[GivenTo3]
          ,[ChallanDate3]
          ,[ReceivedDate3]
          ,[Work4]
          ,[GivenTo4]
          ,[ChallanDate4]
          ,[ReceivedDate4]

So please tell me how to update currentreport table as it has 200 entries and challan table has 700 enteries.

/* check if this is working */ Step 1 - write select to filter out minDate -

SELECT c.ChallanNo, c.REFERENCENO , c.STEPNO FROM CHALLAN c
INNER JOIN CURRENTREPORT cr
on c.REFERENCENO = cr.REFERENCENO
WHERE RECEIVEDDATE IN (SELECT MIN(RECEIVEDDATE)
FROM CHALLAN cn
GROUP BY (STEPNO))

/* if the above is working */ STEP 2 - update based on the results above

WITH CTE AS (
SELECT c.ChallanNo, c.REFERENCENO , c.STEPNO FROM CHALLAN c
INNER JOIN CURRENTREPORT cr
on c.REFERENCENO = cr.REFERENCENO
WHERE RECEIVEDDATE IN (SELECT MIN(RECEIVEDDATE)
FROM CHALLAN cn
GROUP BY (STEPNO))
)

UPDATE CURRENTREPORT SET WORK1 = ch.STEPNO FROM CURRENTREPORT c INNER JOIN cte ch 
on c.referenceNo = ch.referenceNo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM