I need to do a query that brings values of 2 rows into one
Assuming there is a
seq
column that indicates the order of the rows, by
id
, and that
id
identifies each pair in a unique way, here's a suggestion:
-- código #1
SELECT id, valor,
max(case when seq = 1 then banco end) as [banco 1],
max(case when seq = 2 then banco end) as [banco 2]
from nome_tabela
group by id, valor;
But if the seq
column does not exist and both place the order in which the bank names are listed, here's another option:
-- código #2
with tabela_seq as (
SELECT *,
seq= row_number() over (partition by id order by (SELECT 0))
from nome_tabela
)
SELECT id, valor,
max(case when seq = 1 then banco end) as [banco 1],
max(case when seq = 2 then banco end) as [banco 2]
from tabela_seq
group by id, valor;
In the two above codes you should replace nome_tabela
with the name of the table containing the data.
I will improve my question, (...)
The RECPAG field defines the bank that pays = p and the one that receives = R,
Here is code # 1 updated, considering the additional information:
-- código #1 v2
SELECT NUM, VALOR, DATA,
max(case when RECPAG = 'P' then BANCO end) as [BANCO P],
max(case when RECPAG = 'R' then BANCO end) as [BANCO R],
TIPO
from nome_tabela
group NUM, VALOR, DATA, TIPO;