Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to repeat each row twice

I have a requirement for a report and I would like my sql query to repeat each row twice.

Example :

  **Table 1**
   Id   Name
   1     Ab
   2     Cd
   3     Ef

I want to write a query which outputs the following :

  1   Ab
  1   Ab
  2   Cd
  2   Cd
  3   Ef
  3   Ef

Is there a way I can do it ?

I cannot think of anything except using union

Select Id, name from Table1 union select Id, name from Table1
like image 950
CodeNinja Avatar asked Nov 03 '14 15:11

CodeNinja


People also ask

How do I duplicate every cell in Excel?

Select all your data. Copy it by pressing Ctrl + C. Go to the cell below your data. Paste your data by pressing Ctrl + V.

How do you repeat rows in R?

In R, the easiest way to repeat rows is with the REP() function. This function selects one or more observations from a data frame and creates one or more copies of them. Alternatively, you can use the SLICE() function from the dplyr package to repeat rows.


2 Answers

You can use a union all. A union will not work, because it will eliminate duplicates. Another way is a cross join:

select id, name
from table1 t1 cross join
     (select 1 as n union all select 2) n;
like image 68
Gordon Linoff Avatar answered Oct 09 '22 12:10

Gordon Linoff


You can also use UNION ALL, put them under CTE (Common Table Expression) and Order By Id:

WITH CTE AS
( 
SELECT Id, Name FROM Table_1
    UNION ALL
SELECT Id, Name FROM Table_1
)
SELECT Id, Name
FROM CTE
ORDER BY Id;

As this will reorder them and stacked them as duplicates

like image 1
Saurav Sharma Avatar answered Oct 09 '22 11:10

Saurav Sharma