请教一个多表查询统计问题!
现有三个表,结构如下
表a
djbh,djbs,djlx,rq,times,je
表b
djbh1,djbs,djlx,rq,times,je
表c
djbh2,djbs,djlx,rq,times,je
其中rq,times分别存放日期与时间,为字符型字段(原来的数据库如此)
XSA01646102XSA216 2007-05-1419:35:581034.00
XSA01646103XSA216 2007-05-1414:36:081305.50
XSA01646104XSA216 2007-05-1419:36:233198.30
XSA01646105XSA216 2007-05-1519:36:352590.49
XSA01646106XSA216 2007-05-1419:37:113490.80
XSA01646107XSA216 2007-05-1412:37:221490.20
XSA01646108XSA216 2007-05-1519:37:332739.00
XSA01646109XSA216 2007-05-1409:37:431145.56
XSA01646110XSA216 2007-05-1619:37:521278.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 '