SQL从一个表加入不同的项

时间:2016-10-05 01:17:24

标签: sql

我有一张桌子 Tablename = table01

ID    Item    value
4      a       10
5      b       12
5      c       15

和我的sql

select value as b from table01 where ID = 5 and Item = b
select value as c from table01 where ID = 5 and Item = c

我如何加入这两个sql?

这是我想象的结果

b     c
12    15

3 个答案:

答案 0 :(得分:0)

这是一种方法:

select t1.id, t1.value as b, t2.value as c
from table1 t1 join
     table1 t2
     on t1.id = t2.id and t1.item = 'b' and t2.item = 'c';

答案 1 :(得分:0)

SELECT MAX( CASE WHEN Item = 'b' THEN value END ) AS b,
       MAX( CASE WHEN Item = 'c' THEN value END ) AS c
  FROM table01;

答案 2 :(得分:0)

以下是使用Conditional Aggregate

的一种方法
select max(case when Item = 'b' then value end),
       max(case when Item = 'c' then value end)
from yourtable
Where ID = 5 
  and Item in ( 'b' , 'c')

注意:这考虑ID& ITEM组合不重复。如果它是重复的,那么您将最多value重复