简体   繁体   中英

sql sum 2 column values and sort records by 3 columns

I have columns - ip, port, pair, pair_status, length, length_to_fault, add_date. I need to sort everything by port, and each port has a pair(A,B,C,D) atleast once. when its sorted, i need to sort even more - i need to sort each pair in exact port.

Currently i have select that does everything that i need but just with a length.

I want to change this fragment so it could check - if length = N/A, then it takes length_to_fault and if length_to_fault = N/A, then it takes length. My idea is just to combine these 2 columns into 1. Also each record has value on one column only(it can be length or length_to_fault). So far i have this-

Select d.*
from (select d.*, lead(length::float) over (partition by port_nbr, pair order by d.add_date) as next_length
      from diags d
      where length !='N/A'
     ) d

This works perfectly, but there is records that has N/A in length, but value is inside length_to_fault so this select doesn't take that record. Is there a way to edit this fragment to include length_to_fault too? Maybe i can sum these two columns into one? Also length/length_to_fault is chars in database, so i must change it to float in this select.

You can use a case expression:

Select d.*
from (select d.*,
             lead( (case when length <> 'N/A' then length else length_to_fault end)::float) over (partition by port_nbr, pair order by d.add_date) as next_length
      from diags d    
     ) d

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