将数据合并为一行

时间:2017-06-25 17:51:17

标签: sql postgresql postgresql-9.4

我有以下数据:

materials
==========================
id       | quantity |type
---------+----------+-----
1        |111       |1
2        |240       |2
3        |412       |2
4        |523       |1

为了简化示例,我们要说我需要按类型选择材料,所以理想的结果看起来像这样:

id       | quantity |type |id       | quantity |type
---------+----------+-----+---------+----------+-----
1        |111       |1    |2        |240       |2
4        |412       |1    |3        |412       |2

数据将完美匹配,因此不会成对出现空条目 到目前为止,我只能想到union,就像那样:

select * from materials where type = 1
union all
select * from materials where type = 2

但显然,这不是我想要的。这有可能吗?
附:请不要简化...where type in (1,2)的答案,因为实际情况不能像那样合并。

2 个答案:

答案 0 :(得分:1)

您可以为类型1和2加入单独的查询。使用row_number()函数

进行Eeach查询
create table materials(
  id integer primary key,
  quantity integer,
  type integer
);

insert into materials values
  (1, 111, 1),
  (2, 240, 2),
  (3, 412, 2),
  (4, 523, 1),
  (5, 555, 2),
  (6, 666, 1);

select * 
  from (
    select *, row_number() over (order by id) as rownum
      from materials
      where type=1
    ) t1 inner join (
    select *, row_number() over (order by id) as rownum
      from materials
      where type=2
    ) t2 on t1.rownum = t2.rownum

您可以在此处试用:http://rextester.com/XMGD76001

参考文献

答案 1 :(得分:1)

假设“条件将找到确切需要配对的实体”会产生一个名为pairs的表格,其中包含id1列和id2

select
    p.id1,
    m1.quantity,
    m1.type,
    p.id2,
    m2.quantity,
    m2.type
from
    pairs p
    inner join materials as m1 on m1.id=p.id1
    inner join materials as m2 on m2.id=p.id2;