简体   繁体   中英

SQL Comparing Two Columns in same table and update in another table

Table:1

Col1    Col2    Updated Dated   
100     200     01-01-99    
200     300     02-01-99    
300     400     03-01-99    
400     500     04-01-99    
700     900     

Table 2:

Col New Updated Data
100 500
700 900
1000    No Values
2000    No Values

From table 1 i want to compare col1 and col2 row by row or simple query find the value like 100 assinged to 200 but 200 assinged 300 like etc.. finally 400 assinged into 500. I want retrive the 500 fianlly then assinged into 100.its kind of Zig zag comparsion . how do do in SQL.

As I understand you have something like linked lists and for each linked list you want to get min and max id.

If you are using SQL Server this should work straight away, otherwise I think you will be able to apply the same method to other rdbms.

Table declaration and test values insert:

CREATE TABLE #t 
(
    Col1 int,
    Col2 int 
)

INSERT INTO #t VALUES (100, 200), (200, 300 ), (300, 400), (400, 500), (700, 900)

And the actual code:

SELECT MIN(Col1) AS Col, MAX(Col2) AS New FROM 
(
    SELECT SUM(SeqIDStart) OVER (ORDER BY Col1 ASC) AS SeqID, * 
    FROM (
        SELECT
            CASE WHEN LAG(B.Col1, 0, NULL) OVER (ORDER BY a.Col1 ASC) IS NULL THEN 1 ELSE 0 END AS SeqIDStart,
            a.col1 AS Col1, a.Col2 AS Col2, B.Col1 AS adjsCol
        FROM
            #t a
        LEFT JOIN
            #t b
        ON a.col1 = b.col2
        WHERE a.Col1 IS NOT NULL
    ) a
) b
GROUP BY SeqID

I hope this will help

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