简体   繁体   中英

SQL compare value in column

I need to compare power value last Character W1 with W6, W2 with W7, W3 with W8, etc. If power value is different then I need to output the cell & power info.

  cell   | power 
---------+-------
 HUNDAW1 |   300
 HUNDAW2 |   300
 HUNDAW3 |   300
 HUNDAW6 |   300
 HUNDAW7 |   320
 HUNDAW8 |   300

compare cells power. different power values

HUNDAW1 & HUNDAW6 
HUNDAW2 & HUNDAW7 
HUNDAW3 & HUNDAW8 

  cell   | power 
---------+-------
 HUNDAW2 |   300
 HUNDAW7 |   320
with t (cell, power) as ( values
    ('HUNDAW1',300),
    ('HUNDAW2',300),
    ('HUNDAW3',300),
    ('HUNDAW6',300),
    ('HUNDAW7',320),
    ('HUNDAW8',300)
)
select
    t0.cell as t0_cell, t0.power as t0_power,
    t1.cell as t1_cell, t1.power as t1_power
from
    t t0
    inner join
    t t1 on t0.cell < t1.cell
where
    t0.power <> t1.power
    and
    (t0.cell, t1.cell) in (
        ('HUNDAW1','HUNDAW6'),('HUNDAW2','HUNDAW7'),('HUNDAW3','HUNDAW8')
    )
order by t0.cell, t1.cell
;
 t0_cell | t0_power | t1_cell | t1_power 
---------+----------+---------+----------
 HUNDAW2 |      300 | HUNDAW7 |      320
with    t as
        (
            select  cell,power
                   ,count(*)     over ()               as cnt
                   ,row_number() over (order by cell)  as rn

            from    mytable
        )

select      t1.cell,t1.power

from                t as t1

            join    t as t2

            on      t2.rn = (t1.rn + (t1.cnt/2) - 1) % t1.cnt + 1

where       t1.power <> t2.power

order by    t1.cell      

+---------+-------+
| cell    | power |
+---------+-------+
| HUNDAW2 | 300   |
+---------+-------+
| HUNDAW7 | 320   |
+---------+-------+

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