3

我有以下 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

4 回答 4

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
于 2013-09-30T14:33:50.587 回答
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]
于 2013-09-30T14:37:20.727 回答
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  
于 2013-09-30T14:46:24.383 回答
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,然后从这两个 CTE 的内部连接中选择

于 2013-09-30T14:45:37.137 回答