Search code examples
sqldb2case-expression

Use of CASE statement values in THEN expression


I am attempting to use a case statement but keep getting errors. Here's the statement:

select TABLE1.acct,
        CASE
          WHEN TABLE1.acct_id in (select acct_id 
                                    from TABLE2 
                                group by acct_id 
                                  having count(*) = 1 ) THEN
             (select name 
                from TABLE3 
               where TABLE1.acct_id = TABLE3.acct_id)
          ELSE 'All Others'
        END as Name
   from TABLE1

When I replace the TABLE1.acct_id in the THEN expression with a literal value, the query works. When I try to use TABLE1.acct_id from the WHEN part of the query, I get a error saying the result is more than one row. It seems like the THEN expression is ignoring the single value that the WHEN statement was using. No idea, maybe this isn't even a valid use of the CASE statement.

I am trying to see names for accounts that have one entry in TABLE2.

Any ideas would be appreciated, I'm kind of new at SQL.


Solution

  • First, you are missing a comma after TABLE1.acct. Second, you have aliased TABLE1 as acct, so you should use that.

    Select acct.acct
        , Case 
            When acct.acct_id in ( Select acct_id 
                                    From TABLE2 
                                    Group By acct_id 
                                    Having Count(*) = 1 ) 
                Then ( Select name 
                        From TABLE3 
                        Where acct.acct_id = TABLE3.acct_id
                        Fetch First 1 Rows Only) 
            Else 'All Others' 
            End as Name 
    From TABLE1 As acct
    

    As others have said, you should adjust your THEN clause to ensure that only one value is returned. You can do that by add Fetch First 1 Rows Only to your subquery.