name | id | title | type |
---|---|---|---|
x | 1 | 开始标题 | a |
x | 1 | 中标题 | b |
x | 1 | 结束标题 | c |
筛选出 a 和 c的拼成一条数据
name | id | Btitle | Etitle |
---|---|---|---|
x | 1 | 开始标题 | 结束标题 |
不知道sql应该如何写 用到什么函数
select a.name,a.id,a.title btitle,b.title etitle from 表 a left join 表 b on a.id=b.id and a.type='a' and c.type='c'
楼上的其实是对这个表分别查两次,一次取A,一次取C,然后join,当然只有一行。
一般情况下,这种需求常见的写法是这个样子的
select name,id,
max(case when type='A' then title end) BTITLE,
max(case when type='C' then title end) ETITLE
from 表 where type in ('A','C')
group by name,id
如果是oracle,更舒服的写法应该是
select * from 表 pivot (max(title) for type in ('A' BTITLE,'C' ETITLE))