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

SQL 多表联合查询
如例:
  表1:A002 201211 2012-11-15
  A002 201211 2012-11-30
  表2:A002 201211 2012-11-11
  A002 201211 2012-11-28

要得到结果:
  A002 201211 2012-11-15 2012-11-11
  A002 201211 2012-11-30 2012-11-28
怎么办呢?在线苦等!!!!



------解决方案--------------------
SQL code

create table t1
(a varchar(6),b varchar(8),c date)

create table t2
(a varchar(6),b varchar(8),c date)

insert into t1
select 'A002', '201211', '2012-11-15' union all
select 'A002', '201211', '2012-11-30'

insert into t2
select 'A002', '201211', '2012-11-11' union all
select 'A002', '201211', '2012-11-28'


select x.a,x.b,x.c,y.c
from
(select a,b,c,row_number() over(order by getdate()) 'rn' from t1) x
inner join
(select a,b,c,row_number() over(order by getdate()) 'rn' from t2) y
on x.rn=y.rn

/*
a      b        c          c
------ -------- ---------- ----------
A002   201211   2012-11-15 2012-11-11
A002   201211   2012-11-30 2012-11-28

(2 row(s) affected)
*/

------解决方案--------------------
楼主是想按照时间排序,表一的第一条和表二的第一条合并,第二条和第二条合并。。。这样的话二楼的应该可以了。

感觉应该不是这样简单的需求吧
------解决方案--------------------
探讨
如果是:
表1:A002 201211 2012-11-15
A002 201211 2012-11-30
A003 201211 2012-11-25
A003 201211 2012-11-29
A004 201212 2012-12-01
表2:A002 201211 2012-11-11
A002 201211 2012-11-28
A003……

------解决方案--------------------
SQL code
--> 测试数据:[ta]
IF OBJECT_ID('[ta]') IS NOT NULL DROP TABLE [ta]
GO 
CREATE TABLE [ta]([a] VARCHAR(4),[b] INT,[c] DATETIME)
INSERT [ta]
SELECT 'A002',201211,'2012-11-15' UNION ALL
SELECT 'A002',201211,'2012-11-30' UNION ALL
SELECT 'A003',201211,'2012-11-25' UNION ALL
SELECT 'A003',201211,'2012-11-29' UNION ALL
SELECT 'A004',201212,'2012-12-01'

--> 测试数据:[tb]
IF OBJECT_ID('[tb]') IS NOT NULL DROP TABLE [tb]
GO 
CREATE TABLE [tb]([a] VARCHAR(4),[b] INT,[c] DATETIME)
INSERT [tb]
SELECT 'A002',201211,'2012-11-11' UNION ALL
SELECT 'A002',201211,'2012-11-28' UNION ALL
SELECT 'A003',201211,'2012-11-25'

--------------开始查询--------------------------

SELECT  x.a , x.b , x.c , y.c
FROM    (
         SELECT a , b , c , row_id= ROW_NUMBER () OVER (ORDER BY GETDATE ()) FROM ta
        ) x
FULL JOIN /*或者换成left join*/ 
          (
           SELECT a , b , c , row_id= ROW_NUMBER () OVER (ORDER BY GETDATE ()) FROM tb
          ) y
ON      x.row_id = y.row_id
----------------结果----------------------------
/* 
a    b    c    c
A002    201211    2012-11-15 00:00:00.000    2012-11-11 00:00:00.000
A002    201211    2012-11-30 00:00:00.000    2012-11-28 00:00:00.000
A003    201211    2012-11-25 00:00:00.000    2012-11-25 00:00:00.000
A003    201211    2012-11-29 00:00:00.000    NULL
A004    201212    2012-12-01 00:00:00.000    NULL
*/

------解决方案--------------------
select a,b,max(c),max(d)
from (
select a,b,c,null as d
from TB1
union all
select a,b,null as c,c as d
from TB1) as T
group by a,b