patternMinor
Selecting data from multiple rows into a single row
Viewed 0 times
rowsintosinglemultipleselectingfromdatarow
Problem
I have a table that has columns like following. Batch number is a database design thing like row number
I want to create a query that would return this:
How can I do that?
demand_id batch_number debit status customer
34 1 yes
34 2 jack
35 1 no
35 2 kateI want to create a query that would return this:
demand_id debit status customer
34 yes jake
35 no kateHow can I do that?
Solution
Join the table to itself.
So:
Or (if
SQL fiddle.
So:
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;Or (if
batch_number can reliably be used to fetch the 2 rows needed to make a single row: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;SQL fiddle.
Code Snippets
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;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;Context
StackExchange Database Administrators Q#35165, answer score: 8
Revisions (0)
No revisions yet.