日期:2014-05-18  浏览次数:20505 次

求一sql语句 100分
有三个表A,B,C相同结构如下:

Time,Data

如:

A B C

Time Data Time Data Time Data

08:59 12 07:59 1 08:59 23  
09:00 13 09:00 2 11:00 25
10:01 15 11:00 3 12:00 26

以时间排列,组合数据如下:
Time A_Data B_Data C_Data
07:59 1  
08:59 12 23
09:00 13 2
10:01 15
11:00 3 25
12:00 26  


sql 最后精简一些,运行速度快一点,非常感谢,这贴限制最多只能给100分,分不够说一声,我另开贴加分。


非常感谢。


树哥的回复如下,但是表多或者数据量大的时候就相当的慢了,不知道还有没有更快一点的方法?





SQL code
select isnull(isnull(a.time,b.time),c.time) as time,
a.data,b.data,c.data
from a
full join b on a.time=b.time
full join c on a.time=c.time or b.time=c.time
order by 1

/**
time  data        data        data
----- ----------- ----------- -----------
07:59 NULL        1           NULL
08:59 12          NULL        23
09:00 13          2           NULL
10:01 15          NULL        NULL
11:00 NULL        3           25
12:00 NULL        NULL        26

(6 行受影响)
**/


------解决方案--------------------
树哥的这个已经比较简单了 你可以在a,b,c表的time字段加索引。
------解决方案--------------------
SQL code
 只有索引了
CREATE INDEX time_index ON A(time)
CREATE INDEX time_index ON B(time)
CREATE INDEX time_index ON C(time)

------解决方案--------------------
2000数据库不能用with的

探讨
回2楼,之前一个贴你我看你回复了,我运行的时候报with 语法错误,我用的是sql2000 是不是这个原因?

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

--创建一个索引视图
create view v1
as
select time from a
union
select time from b
union
select time from c
go

--按视图查询
select t.time,a.data as A_data,b.data as B_data,c.data as C_data
from v1 t left join a on t.time = a.time
           left join b on t.time = b.time
           left join c on t.time = c.time

------解决方案--------------------
SQL code
SELECT TIME ,SUM(A_DATA) AS A_DATA
   ,SUM(B_DATA) AS B_DATA
   ,SUM(C_DATA) AS C_DATA
FROM (
SELECT TIME ,DATA AS A_DATA,CAST(NULL AS INT) AS B_DATA,CAST(NULL AS INT) AS C_DATA
FROM A
UNION ALL
SELECT TIME ,NULL AS A_DATA,DATA AS B_DATA,CAST(NULL AS INT) AS C_DATA
FROM B
UNION ALL
SELECT TIME ,NULL AS A_DATA,NULL AS B_DATA,DATA AS C_DATA
FROM C
) AS T
GROUP BY TIME

------解决方案--------------------
那用with表达式也是一样的吧
------解决方案--------------------
你的是用2000的只有用view来做了 

探讨
引用:

SQL code

--创建一个索引视图
create view v1
as
select time from a
union
select time from b
union
select time from c
go

--按视图查询
select t.time,a.data as A_data,b.data as B_……