简体   繁体   中英

Aggregating rows in SQL

I want to select 'Y' or 'N' over 'U'- whenever there is a two-row of the same id. However, I want to retain 'U' when there is only one row of an id. Can anyone show an efficient approach to aggregate the following table:

在此处输入图片说明

into something like this:

在此处输入图片说明

I tried the MAX function but it only retains value in alphabetical order and 'U' happens to be in the middle of 'Y' and 'N' therefore MAX function doesn't work as I intended.

Happy to hear your thoughts.

You can use window functions:

select id, ind
from (
    select t.*, row_number() over(
        partition by id 
        order by case ind
            when 'Y' then 1
            when 'N' then 2
            when 'U' then 3
            else 4           -- is this possible?
        end
    ) rn
    from mytable t
) t
where rn = 1

Alternatively, we can turn the strings to numbers, pick the preferred value, and then translate back to the original string :

select id,
    case min(
        case ind
            when 'Y' then 1
            when 'N' then 2
            when 'U' then 3
        end
    )
        when 1 then 'Y'
        when 2 then 'N'
        when 3 then 'U'
        else '??'
    end as ind
from mytable
group by id

Another approach is aggregation:

select id,
       coalesce(max(case when ind = 'Y' then ind end),
                max(case when ind = 'N' then ind end),
                max(case when ind = 'U' then ind end)
               )
from t
group by id;

This simply runs the logic:

  • If there is a 'Y' , return the 'Y' .
  • Otherwise, if there is an 'N' return the 'N' .
  • Otherwise, if there is a 'U' , return the 'U' .

Assuming the fact that you have to select from 'U', 'Y' and 'N' and there are utmost 2 of them present you can simply use Max function with group by.

SELECT id, MAX(Ind)
FROM mytable
GROUP BY id
order by id

This query will work with most of the databases. Be careful with using the above, though its simple and small but it has a lot of constraints. Do test it thoroughly before going into production and take all the test cases into account.

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