Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joining All Rows of Two Tables in SQL Server

My goal is combining all rows in 2 tables. The simplest example I can think of is:

Table 1

Letter
A
B

Table 2

Number
0
1

Combined Table

Letter  Number
   A      0
   B      0
   A      1
   B      1

I have come up with this SQL statement:

select * from 
(
select * From (
    select 'A' as 'Letter'
    UNION
    select 'B' as 'Letter'
) as Letter
) as Letter,
(
select * from (
    select 0 as 'Number'
    UNION
    select 1 as 'Number'
) as Number
) as Number

This works but I don't like it.

  • defining the same alias multiple times
  • 7 select statements? really....

Does anyone know a cleaner way of doing this? I am sure the answer is out there already but I had no idea how to search for it. Thanks all

like image 774
BRomine Avatar asked Dec 31 '13 00:12

BRomine


People also ask

How do I get all rows in two tables in SQL?

(INNER) JOIN : Returns records that have matching values in both tables. LEFT (OUTER) JOIN : Returns all records from the left table, and the matched records from the right table. RIGHT (OUTER) JOIN : Returns all records from the right table, and the matched records from the left table.

Can we full join 2 tables in SQL?

An SQL query can JOIN multiple tables. For each new table an extra JOIN condition is added. Multi-Table JOINs work with SELECT, UPDATE, and DELETE queries.

What join returns all rows from both tables?

Full Outer Join returns all the rows from both the table.

How do I combine rows in SQL?

You can concatenate rows into single string using COALESCE method. This COALESCE method can be used in SQL Server version 2008 and higher. All you have to do is, declare a varchar variable and inside the coalesce, concat the variable with comma and the column, then assign the COALESCE to the variable.


1 Answers

Easy enough with CROSS JOIN...

SELECT *
FROM Table1
CROSS JOIN Table2

Result:

Letter                    Number
------------------------- -----------
A                         0
B                         0
A                         1
B                         1

(4 row(s) affected)
like image 54
Vland Avatar answered Oct 15 '22 20:10

Vland