How do i compare 2 rows from the same table (SQL Server)

后端 未结 6 556
太阳男子
太阳男子 2020-12-02 16:15

I need to create a background job that processes a table looking for rows matching on a particular id with different statuses. It will store the row data in a string to comp

相关标签:
6条回答
  • 2020-12-02 16:30

    Some people find the following alternative syntax easier to see what is going on:

    select t1.value,t2.value
    from MyTable t1
        inner join MyTable t2 on
            t1.id = t2.id
    where t1.id = @id
    
    0 讨论(0)
  • 2020-12-02 16:33

    I had a situation where I needed to compare each row of a table with the next row to it, (next here is relative to my problem specification) in the example next row is specified using the order by clause inside the row_number() function.

    so I wrote this:

    DECLARE @T TABLE (col1 nvarchar(50));
    
    insert into @T VALUES ('A'),('B'),('C'),('D'),('E')
    
    select I1.col1 Instance_One_Col, I2.col1 Instance_Two_Col  from (
     select col1,row_number() over (order by col1) as row_num
     FROM @T
    ) AS I1
    left join (
     select col1,row_number() over (order by col1) as row_num
     FROM @T
    ) AS I2 on I1.row_num = I2.row_num - 1
    

    after that I can compare each row to the next one as I need

    0 讨论(0)
  • 2020-12-02 16:34

    SELECT COUNT(*) FROM (SELECT * FROM tbl WHERE id=1 UNION SELECT * FROM tbl WHERE id=2) a

    If you got two rows, they different, if one - the same.

    0 讨论(0)
  • 2020-12-02 16:38

    OK, after 2 years it's finally time to correct the syntax:

    SELECT  t1.value, t2.value
    FROM    MyTable t1
    JOIN    MyTable t2
    ON      t1.id = t2.id
    WHERE   t1.id = @id
            AND t1.status = @status1
            AND t2.status = @status2
    
    0 讨论(0)
  • 2020-12-02 16:47

    You can join a table to itself as many times as you require, it is called a self join.

    An alias is assigned to each instance of the table (as in the example below) to differentiate one from another.

    SELECT a.SelfJoinTableID
    FROM   dbo.SelfJoinTable a
           INNER JOIN dbo.SelfJoinTable b
             ON a.SelfJoinTableID = b.SelfJoinTableID
           INNER JOIN dbo.SelfJoinTable c
             ON a.SelfJoinTableID = c.SelfJoinTableID
    WHERE  a.Status = 'Status to filter a'
           AND b.Status = 'Status to filter b'
           AND c.Status = 'Status to filter c' 
    
    0 讨论(0)
  • 2020-12-02 16:49
    SELECT * FROM A AS b INNER JOIN A AS c ON b.a = c.a
    WHERE b.a = 'some column value'
    
    0 讨论(0)
提交回复
热议问题