2

I have a Postgres WHEN case query error. How can I fix the query?

SELECT CASE
            WHEN  AccountStatus='Open' 
           THEN
             (
              SELECT  * 
               from Accounts
               where statusID=1
             )

        WHEN  AccountType='Mutual'
           THEN
             (
               SELECT *
               FROM Accounts
               WHERE AccountTypeID=2
             )

   END as Status, *
FROM Accounts

Showing Error:

more than one row returned by a subquery used as an expression

2
  • Please give the table details. Commented Aug 23, 2017 at 20:11
  • Those two subqueries, because they are in the SELECT portion of your query, can only return a single value. I suspect you have more than one record in your Accounts table that has a StatusID=1 or StatusID=2. How would you suspect it would display MANY records in a single record of your result set? If you share some sample data and your desired results we can guide you to a proper way of getting what you want. Commented Aug 23, 2017 at 20:14

2 Answers 2

1

You should try this:-

SELECT *
FROM Accounts
WHERE CASE  WHEN (AccountStatus='Open' ) THEN statusID=1 
            WHEN (AccountType='Mutual')THEN AccountTypeID=2 
      END;
Sign up to request clarification or add additional context in comments.

Comments

1

I think your problem is not a case query, you want to get the table row given as below. If you really want to use case when type query please define the tables in detail.

SELECT *, 'Open' AS Status from Accounts where statusID = 1
UNION ALL
SELECT *, 'Mutual' AS Status FROM Accounts WHERE AccountTypeID = 2 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.