从多行中选择数据到单行

eli*_*erv 6 oracle

我有一个表,其中包含如下列。批号是数据库设计的东西,就像行号

demand_id        batch_number    debit status     customer
     34               1             yes
     34               2                             jack 
     35               1             no                
     35               2                             kate 
Run Code Online (Sandbox Code Playgroud)

我想创建一个会返回这个的查询:

   demand_id         debit status      customer
     34                  yes             jake
     35                  no              kate 
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

Phi*_*lᵀᴹ 8

将表连接到自身。

所以:

select yt1.demand_id, yt1.debit_status, yt2.customer
from yourtable yt1, yourtable yt2
where yt1.demand_id = yt2.demand_id
and yt1.debit_status is not null
and yt2.customer is not null;
Run Code Online (Sandbox Code Playgroud)

或者(如果batch_number可以可靠地用于获取制作单行所需的 2 行:

select yt1.demand_id, yt1.debit_status, yt2.customer
from yourtable yt1, yourtable yt2
where yt1.demand_id = yt2.demand_id
and yt1.batch_number = 1
and yt2.batch_number = 2;
Run Code Online (Sandbox Code Playgroud)

SQL 小提琴


Lei*_*fel 8

按 demand_id 分组并聚合 debit_status / customer。

SELECT Demand_Id
   , Max(Debit_Status) Debit_Status
   , Max(Customer) Customer
FROM yourtable GROUP BY Demand_Id;
Run Code Online (Sandbox Code Playgroud)

如果您的样本不具有代表性,这可能不起作用。

SQL 小提琴(来自 Phil 的数据)。