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

怎样同时统计两个表中的数据
要统计某段时间内所有车型的到车数和销售数
tb_car_type:车型表
vw_car_basic:车辆基本信息,包含到车日期  
vw_car_sale_stat:车辆销售信息,包含销售时间  

我这样写..不对..用子查询是可以..感觉复杂了点,有没其他方法呢?
select   车型=txt,到车数=sum(case   b.车型   when   txt   then   1   else   0   end   ),
    销售数=sum(case   c.车型   when   txt   then   1   else   0   end   )
    from   tb_car_type   a,vw_car_basic   b,vw_car_sale_stat   c  
    where   a.depth=2   and   b.到车日期   between   '2001-1-1 '   and   '2008-1-1 '  
    and   c.销售时间   between   '2001-1-1 '   and   '2008-1-1 '   group   by   txt


------解决方案--------------------



select sum(case b.车型 when txt then 1 else 0 end ),
销售数=sum(case c.车型 when txt then 1 else 0 end )
from tb_car_type a,vw_car_basic b,vw_car_sale_stat c
where a.depth=2 and b.到车日期 between '2001-1-1 ' and '2008-1-1 '
and c.销售时间 between '2001-1-1 ' and '2008-1-1 ' group by txt

------------------
select 车型=txt,
到车数=count(a.*),
销售数=count(b.*)
from vw_car_basic a
left join vw_car_sale_stat b
on a.车型=b.车型 and a.到车日期=b.销售时间
where a.到车日期 between '2001-1-1 ' and '2008-1-1 '
and a.车型= 'txt '

------解决方案--------------------
感觉几个表设计怪怪的:

tb_car_type:车型表
怎么没有车型ID,联接仍然用“车型”。如果其它两表都包含全部车型信息,这张表就是废表。

vw_car_basic:车辆基本信息,包含到车日期
怎么没有“到车数量”字段,统计到车数需要用到count,难道一次不能“到”两台或以上同型号的车么?

vw_car_sale_stat:车辆销售信息,包含销售时间
同上,怎么没有“销售数量”字段,我同时买两台或以上同型号的车,怎么记录?插入多条重复的记录吗?