SQL多次使用子查询表

时间:2014-05-22 14:33:09

标签: sql sql-server

我想从表t中提取数据

 select 
 (select round(avg(High),2) from t where  High!=0)as High,
 (select round(avg(Med),2) from t where Med!=0) as Med,
  (select round(avg(Low),2) from t where  Low!=0) as Low

我的表格是

    select AAAA as High, BBBB as Med, CCCC as Low from TABLE1 where company like '%3m%'
  union all
  select  
  (select round(XXX,2) from TABLE2 where company like '%3m%' and XXX!=0)as High,
 (select round(YYY),2) from TABLE2 where company like '%3m%' and YYY!=0) as Med,
 (select round(ZZZ,2) from TABLE2 where company like '%3m%' and ZZZ!=0) as Low

我想知道如何在不重复使用子查询的情况下使用查询从表t中提取数据(原来我没有)? 我真正想要做的是从两行获得平均值,其中一行不为零 谢谢你的建议!

3 个答案:

答案 0 :(得分:1)

尝试此查询。它使用CASE功能。如果条件不满足,则假定该值为NULL,因此不会计入平均值。

由于您没有开始,您可以使用CTE创建它。

    WITH t as
    (
     select AAAA as High, BBBB as Med, CCCC as Low from TABLE1 where company like '%3m%'
      union all
      select  
      (select round(XXX,2) from TABLE2 where company like '%3m%' and XXX!=0)as High,
     (select round(YYY),2) from TABLE2 where company like '%3m%' and YYY!=0) as Med,
     (select round(ZZZ,2) from TABLE2 where company like '%3m%' and ZZZ!=0) as Low
    )
SELECT 
ROUND(AVG(case when company like '%3m%'and ABC <> 0 then High else null end), 2) High,
ROUND(AVG(case when company like '%3m%'and DEF <> 0 then Medium else null end), 2) Medium,
ROUND(AVG(case when company like '%3m%'and GHI <> 0 then Low else null end), 2) Low
from t;

答案 1 :(得分:0)

你不能因为每个子查询都是不同的 - 在过滤条件下。

答案 2 :(得分:0)

当然你可以:

select
    round(SUM(case when High<>0 then High else 0 end)/SUM(case when High<>0 then 1 else 0 end),2) as High,
    round(SUM(case when Med<>0 then Med else 0 end)/SUM(case when Med<>0 then 1 else 0 end),2) as Med,
    round(SUM(case when Low<>0 then Low else 0 end)/SUM(case when Low<>0 then 1 else 0 end),2) as Low
from
  (
    select AAAA as High, BBBB as Med, CCCC as Low from TABLE1 where company like '%3m%'
    union all
    select round(XXX,2) High, round(YYY,2) Med, round(ZZZ,2) Low from TABLE2 where company like '%3m%'
  )