SQL比较列中的值

时间:2017-01-24 11:53:27

标签: sql postgresql

我需要比较功率值最后一个字符W1和W6,W2和W7,W3和W8等。如果功率值不同,那么我需要输出单元格&电力信息。

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

比较细胞功率。不同的功率值

HUNDAW1 & HUNDAW6 
HUNDAW2 & HUNDAW7 
HUNDAW3 & HUNDAW8 

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

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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   |
+---------+-------+