我正在检索一些计数,例如按季度分组的“新产品”和“销售数量”。我需要计算这些计数的比率。所以,我的查询是这样的:
select YR,
QTR,
MAX(#ofsales) AS '# of Sales',
MAX(#Totalproducts) AS '# of Total Products',
MAX(#ofsales*100/#Totalproducts) AS '% of Products Sold',
MAX(#Totalproducts/#ofsales) AS 'Inventory'
from (union of few tables)
order by YR, QTR
group by YR, QTR;
结果是:
Yr | Qtr |# of Sales|# of Total products|% of Products Sold|Inventory
2016 | 1 | 5231 | 7239 | NULL | NULL
2016 | 2 | 3678 | 4752 | NULL | NULL
我正在使用MAX()运算符,否则,我会收到如下错误:
Column '#ofsales' is invalid in the select list because it is not
contained in either an aggregate function or the GROUP BY clause
在回答@ mypetlion的问题时,这是我没有MAX()函数的查询。
select YR,
QTR,
#ofsales AS '# of Sales',
#Totalproducts AS '# of Total Products',
#ofsales*100/#Totalproducts AS '% of Products Sold',
MAX(#Totalproducts/#ofsales) AS 'Inventory'
from (union of few tables)
order by YR, QTR
group by YR, QTR;
答案 0 :(得分:1)
您可以使用COALESCE函数包装分母。它将检查值是否为NULL并返回您给出的值。由于您试图避免除以零错误,因此可以让它返回1.
select YR,
QTR,
#ofsales AS '# of Sales',
#Totalproducts AS '# of Total Products',
#ofsales*100/#Totalproducts AS '% of Products Sold',
MAX(#Totalproducts/COALESCE(#ofsales, 1)) AS 'Inventory'
from (union of few tables)
order by YR, QTR
group by YR, QTR;
答案 1 :(得分:0)
由于MAX()函数,无法找到使分区在原始Query中工作的方法。因此,作为一种解决方法,我将所有结果导入到一个新表中,然后应用了除法,它运行良好。