在另一个语句中使用语句的结果

时间:2013-09-30 14:27:27

标签: sql

我已经获得了以下2条SQL语句

select 
    Fleet, SUM(hours) as Operating 
from 
    table
where 
    colE = 'Operating' 
    and START_TIME >= '2012-01-01' and END_TIME<='2013-01-01' 
    and FLEET IS NOT NULL
group by 
    fleet 
order by 
    FLEET asc


select Fleet, SUM(hours) as Delay
from table
    where colE='Delay'  and START_TIME>='2012-01-01' and END_TIME<='2013-01-01' and FLEET IS NOT NULL
        group by fleet order by FLEET asc  

我需要这些陈述的结果基本上显示

       select Fleet, (Operating / Delay ) as Calculated Col from table

有人能帮助我引导我如何做到这一点吗? sql的新手,所以我相信我应该使用临时表?

谢谢!

4 个答案:

答案 0 :(得分:2)

简单INNER JOIN应该:

SELECT op.Fleet, (Operating / Delay) AS Calc FROM
(select 
    Fleet, SUM(hours) as Operating 
    from table
    where 
        colE = 'Operating' 
        and START_TIME >= '2012-01-01' and END_TIME<='2013-01-01' 
        and FLEET IS NOT NULL
    group by fleet 
) AS op INNER JOIN (
select Fleet, SUM(hours) as Delay
    from table
    where colE='Delay'  and START_TIME>='2012-01-01'
        and END_TIME<='2013-01-01' and FLEET IS NOT NULL
    group by fleet
) AS de ON op.Fleet = de.Fleet
ORDER BY op.Fleet ASC

答案 1 :(得分:1)

这种情况更为一般,但在类似情况下可能会有所帮助。

您可以像这样选择声明变量中的值。

Declare @X as Decimal, @Y as Decimal
Set @X = (Select [field] from [table] where [conditions])
Set @Y = (Select [field] from [table] where [conditions])

select @X / @Y

更具体地说,您可以使用案例陈述进行查询。

SELECT
    Fleet
    ,SUM(CASE WHEN @colE = 'Operating' THEN hours END) 
    / SUM(CASE WHEN @colE = 'Delay' THEN hours END) as Calculated
FROM table
WHERE [conditions]

答案 2 :(得分:1)

最简单的方法是加入两个结果:

select a.Fleet, (Operating / Delay ) as Calculated_Col
from (select Fleet, SUM(hours) as Operating 
      from table
      where colE = 'Operating' 
      and START_TIME >= '2012-01-01'
      and END_TIME<='2013-01-01' 
      and FLEET IS NOT NULL
      group by fleet) a
join (select Fleet, SUM(hours) as Delay
      from table
      where colE='Delay'
      and START_TIME>='2012-01-01'
      and END_TIME<='2013-01-01'
      and FLEET IS NOT NULL
      group by fleet) b 
      on a.fleet = b.fleet
order by a.FLEET asc  

答案 3 :(得分:0)

如果您的SQL引擎支持CTE(通用表格表达式;例如SQL SErver,其他人也会支持),您可以使用以下内容:

;WITH BaseDataOperating AS 
(
select 
    Fleet, SUM(hours) as Operating 
from 
    table
where 
    colE = 'Operating' 
    and START_TIME >= '2012-01-01' and END_TIME<='2013-01-01' 
    and FLEET IS NOT NULL
group by 
    fleet 
), BaseDataDelay AS 
(
   select 
       Fleet, SUM(hours) as Delay
   from 
       table
   where 
       colE = 'Delay'
       and START_TIME >= '2012-01-01' and END_TIME <= '2013-01-01' 
       and FLEET IS NOT NULL
   group by 
       fleet 
)
SELECT 
   bdo.Fleet, 
   (bdo.Operating / bdd.Delay ) as Calculated_Col 
FROM
   BaseDataOperating bdo
INNER JOIN
   BaseDataDelay bdd ON bdo.Fleet = bdd.Fleet

基本上为“运行”数字创建一个CTE,一个用于“延迟”数字,然后从这两个CTE的内部联接中选择