Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I SELECT multiple columns within a CASE WHEN on SQL Server?

I have searched this site extensively but cannot find a solution.

Here is the example of my query:

SELECT     ActivityID,     Hours = (CASE                  WHEN ActivityTypeID <> 2 THEN                      FieldName = (Some Aggregate Sub Query),                      FieldName2 = (Some other aggregate sub query)                 WHEN ActivityTypeID = 2 THEN                      FieldName = (Some Aggregate Sub Query with diff result),                      FieldName2 = (Some Other Aggregate Sub Query with diff result)            END) 

obviously I'm leaving out a lot of the query, I just wanted to see if it's possible.

I know I probably could just do the "CASE" twice but figured I would ask...

like image 456
Joshua Avatar asked Jan 15 '10 15:01

Joshua


People also ask

How do I select multiple columns based on condition in SQL?

When we have to select multiple columns along with some condition, we put a WHERE clause and write our condition inside that clause. It is not mandatory to choose the WHERE clause there can be multiple options to put conditions depending on the query asked but most conditions are satisfied with the WHERE clause.

How do I select multiple columns in SQL Server?

To select multiple columns from a table, simply separate the column names with commas! For example, this query selects two columns, name and birthdate , from the people table: SELECT name, birthdate FROM people; Sometimes, you may want to select all columns from a table.

Can we use two columns in CASE statement in SQL?

Yes, you can evaluate different columns in the CASE statement.


2 Answers

The problem is that the CASE statement won't work in the way you're trying to use it. You can only use it to switch the value of one field in a query. If I understand what you're trying to do, you might need this:

SELECT     ActivityID,    FieldName = CASE                    WHEN ActivityTypeID <> 2 THEN                       (Some Aggregate Sub Query)                   ELSE                      (Some Aggregate Sub Query with diff result)                END,    FieldName2 = CASE                   WHEN ActivityTypeID <> 2 THEN                       (Some Aggregate Sub Query)                   ELSE                      (Some Aggregate Sub Query with diff result)                END 
like image 107
Josh Anderson Avatar answered Oct 07 '22 17:10

Josh Anderson


No, CASE is a function, and can only return a single value. I think you are going to have to duplicate your CASE logic.

The other option would be to wrap the whole query with an IF and have two separate queries to return results. Without seeing the rest of the query, it's hard to say if that would work for you.

like image 41
Pete McKinney Avatar answered Oct 07 '22 18:10

Pete McKinney