将数据合并为一行
Uniting data into one row
我有以下数据:
materials
==========================
id | quantity |type
---------+----------+-----
1 |111 |1
2 |240 |2
3 |412 |2
4 |523 |1
为了示例的简单起见,假设我需要 select 材料按类型成对,因此理想的结果如下所示:
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
但显然,这不是我要找的。这可能吗?
P.S。请不要简化 ...where type in (1,2)
的答案,因为实际情况不能像那样合并。
您可以加入类型 1 和类型 2 的单独查询。每个查询都带有 row_number()
函数
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
参考资料:
假设 "conditions will find entities that exactly need to be paired" 产生一个名为 pairs
的 table,其列为 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;
我有以下数据:
materials
==========================
id | quantity |type
---------+----------+-----
1 |111 |1
2 |240 |2
3 |412 |2
4 |523 |1
为了示例的简单起见,假设我需要 select 材料按类型成对,因此理想的结果如下所示:
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
但显然,这不是我要找的。这可能吗?
P.S。请不要简化 ...where type in (1,2)
的答案,因为实际情况不能像那样合并。
您可以加入类型 1 和类型 2 的单独查询。每个查询都带有 row_number()
函数
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
参考资料:
假设 "conditions will find entities that exactly need to be paired" 产生一个名为 pairs
的 table,其列为 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;