1

我有一个格式表

    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;
4

2 回答 2

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,这将完全搞砸:)

于 2012-06-11T20:25:46.443 回答
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
于 2012-06-11T20:26:30.213 回答