T SQL Merge Two Lines in One

Asked

Viewed 1,338 times

1

inserir a descrição da imagem aqui

inserir a descrição da imagem aqui

I have a common id (103307) and would like to join two lines in one. From image 1 and leave as image 2. It is possible?

  • The untitled2 column of the first query will always have the values 1 and 2 to indicate the first and second lines?

2 answers

1

Considering that the column Untitled2 will contain line ordering, for the same id value, here is suggestion using classic pivot:

-- código #1
SELECT id, 
       max(case when C1 = 1 then 1 end) as nC1,
       max(case when C1 = 1 then C2 end) as nC2,
       max(case when C1 = 2 then 2 end) as nC3,
       max(case when C1 = 2 then C2 end) as nC4
  from tabela
  group by id;

In the code above C1 is the column Untitled2 and C2 is the column Untitled3, considering the first image.


As a matter of curiosity, here’s another solution:

-- código #2
SELECT T1.id, 
       T1.C1 as nC1, T1.C2 as nC2,
       T2.C1 as nC3, T2.C2 as nC4
  from tabela as T1
       left join tabela as T2 on T1.id = T2.id
  where T1.C1 = 1
        and (T2.id is null or T2.C1 = 2);
  • Solution 1 solved my problem. Thank you. Because I could not join, since I do not have two tables, even more than in fact the "table" is a sub-select

0

Suggestion 1

If the column untitled2 is a sequential for records of the same id, query can be the following:

select t1.untitled1
      ,t1.untitled2
      ,t1.untitled3
      ,t2.untitled2 as untitled3 
      ,t2.untitled3 as untitled4
  from tabela as t1
  join tabela as t2 on t1.untitled1 = t2.untitled1
 where t1.untitled2 < t2.untitled2; 

Solution 2

If the values contained in untitled2 and untitled3 can repeat for same records id, such as, for example:

untitled1 untitled2 untitled3 
103307    1         10
103307    1         10

In this case, as we can have duplicate records in the table, it will be necessary to create a idrow to distinguish the records.

Using Sqlserver CTE, we can mount a subquery to add the column idrow before doing Join to generate the final result:

with tab_temp (idrow, untitled1, untitled2, untitled3)
as
(
   select row_number() over (order by untitled1)  as idrow
         ,untitled1
         ,untitled2
         ,untitled3
     from tabela
)
select t1.untitled1
      ,t1.untitled2
      ,t1.untitled3
      ,t2.untitled2 as untitled3 
      ,t2.untitled3 as untitled4
  from tab_temp as t1
  join tab_temp as t2 on t1.untitled1 = t2.untitled1
  where t1.idrow < t2.idrow;

For testing

I created an example running online at http://sqlfiddle.com/#! 6/c7ae9e/11

Browser other questions tagged

You are not signed in. Login or sign up in order to post.