ASalameh
ASalameh

Reputation: 803

Select same column with different conditions to separate columns

I need to select specific column with different conditions and combine the result in different columns and one result .

I tried something like this , its wrong but to clear the idea

Select [ObjectiveKey] as column_1  from [Objectives] where [ID] = 9
union
Select [ObjectiveKey] as column_2 from [Objectives] where [ID] = 12
union
Select [ObjectiveKey] as column_3 from [Objectives] where [ID] = 11
union
Select [ObjectiveKey] as column_4 from [Objectives] where [ID] = 10
union
Select [ObjectiveKey] as column_5 from [Objectives] where [ID] = 32

And the result should look like this

enter image description here

Upvotes: 0

Views: 90

Answers (2)

Felix Pamittan
Felix Pamittan

Reputation: 31879

You can do it using conditional aggregation:

SELECT
    column_1 = MAX(CASE WHEN ID = 9 THEN ObjectiveKey END),
    column_2 = MAX(CASE WHEN ID = 12 THEN ObjectiveKey END),
    column_3 = MAX(CASE WHEN ID = 11 THEN ObjectiveKey END),
    column_4 = MAX(CASE WHEN ID = 10 THEN ObjectiveKey END),
    column_5 = MAX(CASE WHEN ID = 32 THEN ObjectiveKey END)
FROM Objectives
WHERE
    ID IN(9, 12, 11, 10, 32)

As suggested in the comment, you may want to add a filter for ID.

Upvotes: 2

Turophile
Turophile

Reputation: 3405

I can't see your expected result because it is a graphic, but I think what you need is :

Select [ObjectiveKey] as column_1  from [Objectives] where [ID] IN (9,10,11,12,32)

Upvotes: 0

Related Questions