如果我有如下表格,
tid pid bid fl fq fo
---------------------------
7114 3823 2341 3 1 1
7114 3823 2340 0 0 0
7114 3823 2350 0 0 0
7114 3850 4515 0 0 0
7114 3474 2350 0 0 0
7114 3474 2340 1 2 1
从此表中我需要通过分组{{1}来获取列pid
,bid
,fl
和fq
的行fo=1
}
,预期输出为:
pid
注意:例如(考虑表格)第1行和第2行具有相同的pid,即。pid bid fl fq fo
----------------------
3823 2341 3 1 1
3823 2340 3 1 1
3823 2350 3 1 1
3474 2350 1 2 1
3474 2340 1 2 1
,在这两行中,一行有3823
(即第1行)所以我需要获取第一行的fo=1
以及第二行的pid
,fl
和fq
,因此输出应为
bid
示例数据:
pid bid fl fq fo
----------------------
3823 2341 3 1 1
3823 2340 3 1 1
3823 2350 3 1 1
答案 0 :(得分:2)
试试这个:
select distinct c1.pid
, c2.fl
, c2.fq
, c2.bid
from tmp.com c1
inner join tmp.com c2
on c1.pid = c2.pid
and c2.fo = 1
output:
3474 1 2 2340
3823 3 1 2341
distinct
是防止重复的必要条件,如果可以的话,您还可以在更多字段上join
。
答案 1 :(得分:1)
我猜您是否正在使用PostgreSQL
数据库,如果是这样,请尝试以下操作:
1。)创建一个临时表
create temp table temp_com as select pid,bid,fl,fq,fo from com limit 0;
2。)使用CTE根据您的标准获取值
使用CTE 插入 - pid
,bid
至temp_com
with cte as (
select c1.pid,c1.bid,c1.fl,c1.fq,c1.fo
from com c1 inner join com c2 using (pid)
where c2.fo=1
)
insert into temp_com (pid,bid) (select pid,bid from cte);
来自CTE的 更新 - fl
,fq
和fo
with cte as(
select c1.pid,c1.bid,c1.fl,c1.fq,c1.fo
from com c1 inner join com c2 using (pid)
where c2.fo=1
)
update temp_com a
set fl= cte.fl,
fq=cte.fq,
fo=cte.fo
from cte
where a.pid=cte.pid and cte.fo=1; -- gets the row have `fo=1`
结果:select * from temp_com;
pid bid fl fq fo
----------------------
3823 2341 3 1 1
3823 2340 3 1 1
3823 2350 3 1 1
3474 2350 1 2 1
3474 2340 1 2 1