选择具有不同条件的相同列以分隔列

时间:2015-03-25 23:33:32

标签: sql sql-server sql-server-2008

我需要选择具有不同条件的特定列,并将结果组合在不同的列和一个结果中。

我尝试了类似这样的事情,这是错误的,但要明确这个想法

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

结果应该是这样的

enter image description here

2 个答案:

答案 0 :(得分:2)

您可以使用条件聚合来完成:

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)

根据评论中的建议,您可能需要为ID添加过滤器。

答案 1 :(得分:0)

我无法看到您的预期结果,因为它是图形,但我认为您需要的是:

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