当前位置: 代码迷 >> VFP >> 两个表比较的SQL语句如何写?多谢。
  详细解决方案

两个表比较的SQL语句如何写?多谢。

热度:3314   发布时间:2013-02-26 00:00:00.0
两个表比较的SQL语句怎么写?谢谢。。
两个表比较的SQL语句怎么写?谢谢。。

本周时间是2011-12-7到2011-12-12,本周的时间可变的,从本周清单取。

有两个表。1.本周故障清单,2.前期故障清单(数据量很大),比较得出重复故障数和清单。

重复故障是指:本周发生的故障与以前发生的故障的故障名称相同的故障,如有重复,那本周和以前都要统计。
如果非本周有重复的故障,本周没有发生,不要统计。

重复故障数:包括本周和以前一起重复的总数。

1.前期的故障清单

故障名称 发生时间 修复时间

aa 2011-12-05 11:26 2011-12-10 09:30
bb 2011-12-05 11:55 2011-12-05 15:31
cc 2011-12-05 11:55 2011-12-05 14:30
dd 2011-12-05 12:35 2011-12-05 17:40
ee 2011-12-05 16:39 2011-12-05 18:10
ff 2011-12-05 17:23 2011-12-05 18:05
mm 2011-12-05 19:37 2011-12-07 23:26
gg 2011-12-06 10:45 2011-12-06 14:34
hh 2011-12-06 11:00 2011-12-06 14:30
ii 2011-12-06 12:15 2011-12-06 16:47
jj 2011-12-06 16:04 2011-12-06 16:33
kk 2011-12-06 16:19 2011-12-07 16:42
ll 2011-12-06 17:00 2011-12-07 15:06
mm 2011-12-06 17:37 2011-12-07 12:26
nn 2011-12-06 19:28 2011-12-06 20:37
nn 2011-12-06 22:28 2011-12-06 23:37

-----------------------------------------------

2.本周故障清单

故障名称 发生时间 修复时间
oo 2011-12-07 00:14 2011-12-07 00:21
pp 2011-12-07 09:03 2011-12-07 12:06
qq 2011-12-07 09:57 2011-12-07 10:21
aa 2011-12-07 10:29 2011-12-09 11:13
xx 2011-12-07 11:31 2011-12-07 14:37
cc 2011-12-07 15:15 2011-12-07 17:08
ff 2011-12-07 18:32 2011-12-07 20:29
aa2 2011-12-08 10:56 2011-12-09 08:45
aa3 2011-12-08 11:41 2011-12-08 13:00
aa4 2011-12-08 20:45 2011-12-09 10:00
bb 2011-12-08 20:56 2011-12-08 21:10
aa 2011-12-10 11:10 2011-12-10 16:33
bb 2011-12-10 11:37 2011-12-10 11:48
aa 2011-12-11 09:55 2011-12-11 14:45
hh 2011-12-11 13:24 2011-12-11 16:30
----------------------------------------------------

结果:

故障名称 重复次数
aa 4
bb 3
cc 2
ff 2
hh 2


重复清单:


故障名称 发生时间 修复时间
aa 2011-12-05 11:26 2011-12-10 09:30
aa 2011-12-07 10:29 2011-12-09 11:13
aa 2011-12-10 11:10 2011-12-10 16:33
aa 2011-12-11 09:55 2011-12-11 14:45
bb 2011-12-05 11:55 2011-12-05 15:31
bb 2011-12-08 20:56 2011-12-08 21:10
bb 2011-12-10 11:37 2011-12-10 11:48
cc 2011-12-05 11:55 2011-12-05 14:30
cc 2011-12-07 15:15 2011-12-07 17:08
ff 2011-12-05 17:23 2011-12-05 18:05
ff 2011-12-07 18:32 2011-12-07 20:29
hh 2011-12-06 11:00 2011-12-06 14:30
hh 2011-12-11 13:24 2011-12-11 16:30


------解决方案--------------------------------------------------------
在两表 故障名称 上建立索引
select a.故障名称,count(*) as js from 本周故障清单 a inner join 前期的故障清单 b 
on a.故障名称=b.故障名称 having count(*)>=2 into curs dd

select * from (select * from 前期的故障清单 union all select * from 本周故障清单) a
inner join dd b on a.故障名称=b.故障名称

or

select * from (select * from 前期的故障清单 union all select * from 本周故障清单) a1
inner join 
(select a.故障名称,count(*) as js from 本周故障清单 a inner join 前期的故障清单 b
on a.故障名称=b.故障名称 having count(*)>=2) b1
on a1.故障名称=b1.故障名称

------解决方案--------------------------------------------------------
select a.故障名称,a.CNT_CW+count(b.故障名称)
from
(
select 故障名称,count(*) as CNT_CW
from 本周故障清单 
group by 故障名称
) a left join (
select 故障名称
from 前期的故障清单 
group by 故障名称
) b
group by a.故障名称,a.CNT_CW
having a.CNT_CW+count(b.故障名称)>1
  相关解决方案