Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joining two columns on a table in SQL

Tags:

sql

I have a problem that is quite simple to understand, but for me it is not that simple to implement.

I have a table named Time:

-----------------------------------
 DAY     TIME1     TIME2
-----------------------------------
 1       08.00     09.40
 1       09.40     10.00
 1       10.00     11.40
 2       08.00     08.50
 2       08.50     10.40
 ----------------------------------

What I want to get is like:

-------------------
 DAY     TIME     
-------------------
 1       08.00     
 1       09.40     
 1       10.00     
 1       11.00     
 2       08.00     
 2       08.50     
 2       10.40     
 ------------------

I have tried this code:

SELECT DISTINCT sub.val FROM (
  SELECT Time1 AS val FROM Time
  UNION ALL
  SELECT Time2 AS val FROM Time
) AS sub

And it is only return the Time column. I have no idea about joining the "Day" column. While I am trying to add the "Day" after the "DISTINCT sub.val", it got error. How to do it?

Thank you very much.

like image 222
mrjimoy_05 Avatar asked Apr 05 '12 13:04

mrjimoy_05


People also ask

Can you join columns in SQL?

If you'd like to get data stored in tables joined by a compound key that's a primary key in one table and a foreign key in another table, simply use a join condition on multiple columns. In one joined table (in our example, enrollment ), we have a primary key built from two columns ( student_id and course_code ).

How do I merge two columns in a single column in SQL?

How to merge two column value as one in SQL Server? To merge two columns value as one, we can concatenate it as one and use alias for that value. This is the simplest way to do it. Here the combination of FirstName and LastName is separated by a blank space and given as FullName.

Can we join two tables on two columns SQL?

The SQL JOIN is one of the basic tools for data analysts working with SQL. Relational databases are built in a way such that analytical reports usually require combining information from several tables. You'll be joining tables, sometimes by one column and other times by two or more columns.


2 Answers

select distinct day, time1 from mytab
union
select distinct day, time2 from mytab
like image 103
Randy Avatar answered Oct 04 '22 07:10

Randy


SELECT DISTINCT sub.Day, sub.val as Time FROM (
  SELECT Day, Time1 AS val FROM Time
  UNION ALL
  SELECT Day, Time2 AS val FROM Time
) AS sub
like image 27
Sam DeHaan Avatar answered Oct 04 '22 09:10

Sam DeHaan