Search code examples
sqlrow

SQL Select row depending on values in different columns


I've already found so many answers here but now I can't seem to find any to my specific problem.

I can't figure out how to select a value from a row depending on the value in different columns

with the below table, I want to achieve the following results.

enter image description here

in case the value in column stdvpuni = 1 then return values / contents from this row for the article (column art).

in case the value in column stdvpuni = 0 then return values / contents from the row where STDUNIABG = 1 for this article (column art).

enter image description here


Solution

  • You seem to want one row part art, based on the content of other rows. That suggests using row_number():

    select t.*
    from (select t.*,
                 row_number() over (partition by art order by stdvpuni desc, STDUNIABG desc) as seqnum
          from t
         ) t
    where seqnum = 1;
    

    You don't specify what to do if neither column is 1. You might want a where clause (where 1 in (stdvpuni, STDUNIABG)) or another condition in the order by.