MS SQL中的案例函数

时间:2012-06-11 20:21:55

标签: sql-server sql-server-2008

我有一张格式表

    id name flag
  ----------------
    11 Jack  1
    11 Jill  2
    23 Joe   1
    23 John  2
    23 Sam   1
    46 White 2
    46 Dan   2
    57 Dave  1

我正在尝试返回格式表(基于特定id的标志),如

    id name_1 name_2
   ------------------
    11 Jack   Jill
    23 Joe    John
    23 Sam    John
    46 NULL   White
    46 NULL   Dan
    57 Dave   NULL

我尝试了这个查询,但没有给出预期的结果。

select id,
case flag when 1 then name end as name_1,
case flag when 2 then name end as name_2
from temp;

2 个答案:

答案 0 :(得分:1)

我认为你不能使用案例。然而,这应该可以解决问题:

select t1.id, t1.name as name_1, t2.name as name_2
from temp t1
    inner join temp t2 on t1.id = t2.id and t1.flag = 1 and t2.flag = 2

我不确定你是否可以从同一个查询中得到部分结果,所以你总是可以联合找到这些......

select t1.id, t1.name as name_1, t2.name as name_2
from temp t1
    inner join temp t2 on t1.id = t2.id and t1.flag = 1 and t2.flag = 2

union

select t1.id, t1.name as name_1, t2.name as name_2
from temp t1
    left join temp t2 on t1.id = t2.id and t1.flag = 1 and t2.flag = 2
where t2.id is null

union

select t2.id, t1.name as name_1, t2.name as name_2
from temp t2
    left join temp t1 on t1.id = t2.id and t1.flag = 1 and t2.flag = 2
where t1.id is null

如果有3行具有相同的ID,这将完全搞砸了:)

答案 1 :(得分:1)

您想要加入,而不是选择案例。这样的事情,假设在任一列中都为null:

SELECT a.id, a.name fname, b.name lname from
(SELECT id, name FROM temp WHERE flag = 1) a 
full outer join 
(SELECT id, name FROM temp WHERE flag = 2) b on a.id = b.id

虽然不确定您在这种情况下的期望:

46 NULL   White
46 NULL   Dan