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

三表联查

SQL code

--A表 记录公司财务
cw1     cw2     cw3
60000   200     2010-12-31
--B表记录公司所属行业
CW1     CW2  
60000    银行
--C表记录行业指标平均值
cw1    cw2(毛利润平均值)   CW3
银行    121                  2010-12-31


现在我想要通过查询 公司>行业平均值 的公司。请高手给我看看怎么做。

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

;with 
a as (select * from cw),
b as (select * from hy),
c as (select * from hyzb),
d as (
select a.dm as [代码],a.nawe as [名称] ,b.hy as [行业],a.data  as [日期], 
(a.cw79-a.cw80)/a.cw79 as [毛利润-营业收入],(a.cw82+a.cw83)/(a.cw79-a.cw80)as [营销费用-毛利润] 
from a
inner join b on a.dm=b.dm
inner join c on b.hy=c.hy
where (a.cw79-a.cw80)/a.cw79 >c.cw1 and a.cw79<>0
and (a.cw82+a.cw83)/(a.cw79-a.cw80)> c.cw3
and datepart(yyyy,a.data)=datepart(yyyy,c.data) 
and YEAR(a.data) IN (2008,2009,2010))
select d.* 
from d where dm in
(select dm from d group by dm having count(*)=3)
order by d.hy,d.dm,d.data