Maxqueue
Maxqueue

Reputation: 2454

SQL Server 2012 - Query columns based on condition

I am trying to query for a table based on a condition. For example let's say I have table A with columns c1, c2, c3, c4, and c5.

Pseudo code:

If c5='Y'
Then
    select c1, c2 from A
else
    select c3, c4 from A

I am looking for something like the following:

case when c5='Y' then select c1, c2 from A
else select c3, c4 from A

Any help would be appreciated.

Upvotes: 0

Views: 42

Answers (2)

Maxqueue
Maxqueue

Reputation: 2454

So the following solved the problem i was having:

if(exists(select top 1 1 from A where c5 = 'Y'))
begin
select c1, c2 from A
end
else
begin
select c3, c4 from A
end

Upvotes: 0

Sean Lange
Sean Lange

Reputation: 33581

Your case expression code doesn't make sense logically. You have to put the case expression on the row, not the table. Something like this.

select case when c5 = 'Y' then c1 else c3 end as MyFirstColumn
    , case when c5 = 'Y' then c2 else c4 end as MySecondColumn
from A

Upvotes: 1

Related Questions