日期:2014-05-19  浏览次数:20615 次

请教一个多表查询统计问题!
现有三个表,结构如下
表a
djbh,djbs,djlx,rq,times,je
表b
djbh1,djbs,djlx,rq,times,je
表c
djbh2,djbs,djlx,rq,times,je

其中rq,times分别存放日期与时间,为字符型字段(原来的数据库如此)

XSA01646102 XSA 216   2007-05-14 19:35:58 1034.00
XSA01646103 XSA 216   2007-05-14 14:36:08 1305.50
XSA01646104 XSA 216   2007-05-14 19:36:23 3198.30
XSA01646105 XSA 216   2007-05-15 19:36:35 2590.49
XSA01646106 XSA 216   2007-05-14 19:37:11 3490.80
XSA01646107 XSA 216   2007-05-14 12:37:22 1490.20
XSA01646108 XSA 216   2007-05-15 19:37:33 2739.00
XSA01646109 XSA 216   2007-05-14 09:37:43 1145.56
XSA01646110 XSA 216   2007-05-16 19:37:52 1278.18


现要统计每一时间段内,比如7:00-8:00   ,9:00-10:00的单据数
显示结果需如下:
时间段                         时间段内a的数量       时间段内b的数量       时间段内c的数量
07:00-08:00
08:00-09:00
09:00-10:00
10:00-11:00
11:00-12:00
12:00-13:00
···                        
       


------解决方案--------------------
--試下,没測試

select
right(100+datediff(hour, '2000-1-1 ',[date]),2)+ ':00- '+right(101+datediff(hour, '2000-1-1 ',[date]),2)+ ':00 ' as [时间段],
sum(case when tmp= 'a ' then 1 else 0 end) as [a數量],
sum(case when tmp= 'b ' then 1 else 0 end) as [b數量],
sum(case when tmp= 'c ' then 1 else 0 end) as [c數量]
from
(
select '2000-1-1 '+times as [date], 'a ' as tmp
from a
union all
select '2000-1-1 '+times as [date], 'b ' as tmp
from b
union all
select '2000-1-1 '+times as [date], 'c ' as tmp
from c
) T
group by right(100+datediff(hour, '2000-1-1 ',[date]),2)+ ':00- '+right(101+datediff(hour, '2000-1-1 ',[date]),2)+ ':00 '