SQL Server Evaluate two rows independently of one another in SQL

piwo6bdm  于 2023-11-16  发布在  其他
关注(0)|答案(1)|浏览(101)

I'm trying to evaluate 2 rows independently. e.g. check if row1=4 AND row2 is NOT equal to 2

The query I have is not working. I think its because I'm saying the interface name must be two values at once. Can I do a union here? or does that not apply?

SELECT I.DisplayName, I.Status FROM Interfaces AS I

WHERE  ( I.[InterfaceName] = 'GigabitEthernet1/0/2'  AND  I.[Status] = '4' ) AND  ( I.[InterfaceName] = 'GigabitEthernet1/0/1' AND I.[Status] != '2' )

Here is a table sample of these two items.

1mrurvl1

1mrurvl11#

If you're looking into if table has any two rows that both match some condition you can do a following:

create table Interfaces  (InterfaceName nvarchar(100), status varchar(10))

insert into Interfaces (
    InterfaceName, status
)
values  ('GigabitEthernet1/0/2','4')
,   
('GigabitEthernet1/0/1','1')
,   ('GigabitEthernet1/0/3','2')

SELECT  *
FROM    (
    select  *, COUNT(*) OVER() AS cnt
    from    Interfaces i
    WHERE   (
            (I.[InterfaceName] = 'GigabitEthernet1/0/2' AND I.[Status] = '4')
        OR  (I.[InterfaceName] = 'GigabitEthernet1/0/1' AND I.[Status] != '2')
    )
    ) x
WHERE   cnt >= 2

The OR matches the conditions you're looking for, the COUNT makes sure you get at least two values.

If you have duplicates and want to make sure you get both interfaces and not just duplicate of one interface, it's a bit more complicated. One solution is:

insert into Interfaces (
    InterfaceName, status
)
values  ('GigabitEthernet1/0/2','4')
,   ('GigabitEthernet1/0/1','1')
,   ('GigabitEthernet1/0/1','1')
,   ('GigabitEthernet1/0/3','2')

SELECT  *
FROM    (
        SELECT  *, COUNT(*) OVER() AS cnt
        FROM    (
            select  *, ROW_NUMBER() OVER(PARTITION BY InterfaceName ORDER BY @@SPID) AS rnk
            from    Interfaces i
            WHERE   (
                    (I.[InterfaceName] = 'GigabitEthernet1/0/2' AND I.[Status] = '4')
                OR  (I.[InterfaceName] = 'GigabitEthernet1/0/1' AND I.[Status] != '2')
            )
            ) x
        WHERE   rnk = 1
    ) x
WHERE   x.cnt >= 2

ROW_NUMBER creates a grouping of rows per Interface, for which we only take one, and then by wrapping it in another COUNT(*) OVER() you once again return the two distinct rows

相关问题