在SQL中连接表上的两列

时间:2020-12-08 14:03:10

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:

我有一个名为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?

它只返回时间列。我不知道加入“日”专栏。当我试图在“DISTINCT sub.val”之后添加“Day”时,它出错了。怎么做?

Thank you very much.

非常感谢你。

4 个解决方案

#1


5  

select distinct day, time1 from mytab
union
select distinct day, time2 from mytab

#2


3  

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

#3


3  

try this

尝试这个

SELECT DISTINCT *
FROM (
    SELECT day, time1 FROM Time
    UNION ALL SELECT day, time2 FROM Time
) AS x
ORDER BY x.day

#4


2  

This might help:

这可能有所帮助:

SELECT
    DAY,
    TIME1
FROM
    YourTable AS T
UNION
SELECT
    DAY,
    TIME2
FROM
    YourTable AS T
ORDER BY DAY,TIME1

#1


5  

select distinct day, time1 from mytab
union
select distinct day, time2 from mytab

#2


3  

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

#3


3  

try this

尝试这个

SELECT DISTINCT *
FROM (
    SELECT day, time1 FROM Time
    UNION ALL SELECT day, time2 FROM Time
) AS x
ORDER BY x.day

#4


2  

This might help:

这可能有所帮助:

SELECT
    DAY,
    TIME1
FROM
    YourTable AS T
UNION
SELECT
    DAY,
    TIME2
FROM
    YourTable AS T
ORDER BY DAY,TIME1