1

我有以下 SQL 查询,我想计算一个派生字段 A/B:

select center, month, sum(countA) as A, sum(countB) as B, A/B 
from counter
group by center, month

但是,这句话抛出了一个错误,我希望不再重复总和。有没有办法在单个查询上做到这一点?

4

2 回答 2

2

不幸的是,别名在同一个 select 子句中是未知的。您可以按以下方式进行计算:

select center, month, sum(countA) as A, sum(countB) as B, sum(countA) / sum(countB)
from counter
group by center, month;

您也可以在子查询中执行此操作:

select center, month, A, B, A/B
from (select center, month, usm(countA) as A, sum(countB) as B
      from counter
      group by center, month
     ) t
于 2013-06-06T15:07:52.120 回答
0

您可以执行以下操作:

select center, month, A, B, A/B from
(
    select center, month, sum(countA) as A, sum(countB) as B
    from counter
    group by center, month
)

但是如果 B 为零,您仍然可能会收到错误消息。为了解决这个问题,试试这个:

select center, month, A, B, case when B = 0 then 0 else A/B end from
(
    select center, month, sum(countA) as A, sum(countB) as B 
    from counter
    group by center, month
)
于 2013-06-06T15:09:14.820 回答