I need to do a query that brings values of 2 lines in one
Assuming there is a column seq
indicating the order of the lines, by value of id
, and that id
uniquely identify each pair, 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 there is no column seq
and both make the order in which the names of the banks are listed, here is 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 above two codes nome_tabela
by the name of the table containing the data.
I’ll improve my question, (...)
The RECPAG field defines the paying bank = p and the receiving bank = 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;
Which bank? Mysql, Sqlserver, Postgresql, Oracle? Each has a different way of doing what Cvoce wants. Specify better.
– William John Adam Trindade
Sql Server 2014
– Tulio
it doesn’t make much sense to bring balances in columns, but ok... and the name of it is pivot table, try some of the questions already asked: https://answall.com/search?q=%5Bsql-server%5D+pivot+table
– Rovann Linhalis
Possible duplicate of Turn rows into a select column - PIVOT - SQL Server
– Sorack
Look, it shouldn’t be hard to do what you want. The problem is that as you didn’t explain it properly, you can’t know what you want and so you can’t answer the question. I even tried to come up with an answer, but there’s a lot missing from your question to make it possible. Are banks always cashier and Bradesco? Is the value of the two accounts always the same? If the values differ, what should be done? What is the table name? Which fields are the primary key? Are there other related tables? If there are more than two banks for the same id, how do I relate the records?
– Victor Stafusa
Do you know how many banks will have? Or will it be variable?
– Sorack
Is there a column that indicates the order of the rows, for the same id value? Or does it come either "box | Bradesco" or "Bradesco | box"?
– José Diz