日期:2014-05-17  浏览次数:20721 次

求一关于两个临时表合并的sql语句,
现有两个临时表,
表一: (时间)time (课程总数)lesson
表二:(时间)time (注册人数)register
都是两列,共同的列是:时间(time),
现在打算把两个表合并,保留共同的列time,生成一个新的临时表单。
共有三列: time , lesson , register.
例如: 表一
time lesson
2012-08-16 2
2012-09-02 8

  表二
time register
2012-08-27 4
2012-08-28 3

合并后的表:
time lesson register
2012-08-16 2 
2012-08-27 4
2012-08-28 3
2012-09-02 8

谢谢所有达人的帮助,在线等

------解决方案--------------------
SQL code
CREATE TABLE #T1(
    [TIME]    DATE,
    lesson  int   
)

CREATE TABLE #T2(
    [TIME]    DATE,
    register  INT
)

INSERT INTO #T1  
        ( TIME, lesson )
SELECT '2012-08-16',2 UNION ALL
SELECT '2012-09-02',8 

INSERT INTO #T2
        ( TIME, register )
SELECT '2012-08-27',4 UNION ALL
SELECT '2012-08-28',3

SELECT  CASE WHEN A.[TIME] IS NULL THEN B.[TIME] ELSE A.[TIME] END  AS [TIME],
        A.lesson,B.register
FROM    #T1 A
FULL JOIN #T2 B ON A.TIME = B.TIME
ORDER BY [Time]

DROP TABLE #T1,#T2

------解决方案--------------------
select t0.time,t1.lesson ,t2.register 
from (select time from 表一 union select time from 表二) t0
left join 表一 t1 on t0.time=t1.time
left join 表二 t2 on t0.time =t2.time
order by t0.time
------解决方案--------------------
select time,lesson, null as register from table1
union all
select time, null as lesson, register from table2
------解决方案--------------------
SQL code

-->测试数据
CREATE TABLE #T1(
    time    datetime,
    lesson  int   
)

CREATE TABLE #T2(
    time   datetime,
    register  INT
)

INSERT INTO #T1  
        ( time, lesson )
SELECT '2012-08-16',2 UNION ALL
SELECT '2012-09-02',8 

INSERT INTO #T2
        ( time, register )
SELECT '2012-08-27',4 UNION ALL
SELECT '2012-08-28',3

-->测试查询
select time,lesson, null as register from #T1
union all
select time, null as lesson, register from #T2
-------------------------------------------------
/*
  time                   lesson  register
2012-08-16 00:00:00.000      2    NULL
2012-09-02 00:00:00.000      8    NULL
2012-08-27 00:00:00.000     NULL    4
2012-08-28 00:00:00.000     NULL    3
*/