我无法在我的 SQL 代码中计算除法
Posted
技术标签:
【中文标题】我无法在我的 SQL 代码中计算除法【英文标题】:I cannot calculate a division in my SQL code 【发布时间】:2010-01-28 13:10:23 【问题描述】:以下代码可以正常工作:
select donem, mekankodu, count(yayin_kodu) yc,
SUM(CASE WHEN iade =0 THEN 1 ELSE 0 END) yys
from
( select donem,
bayi_adi,
bayi_kodu,
x.mekankodu,
mekan_adi,
mekan_tipi,
yayin_kodu,
yayin_adi,
sum(x.b2b_dagitim + x.b2b_transfer) sevk,
sum(x.b2b_iade) iade,
sum(x.b2b_dagitim + x.b2b_transfer - x.b2b_iade) satis
from mps_view2 x
where x.donem = '200910'
and x.yayin_kodu in (93,95,98,99,103,174,307,309,311,489,491,495,533,534,538,605,641,642,650,2539,
2697,4560,5049,5772,5950,5980,7318,7440,8086,8524,11161,12707,12708,12709,14376,
15107,15309,15633)
and x.mekankodu in (31851,38569,7123,7403,7481)
group by donem, bayi_adi, bayi_kodu, mekankodu, mekan_adi, mekan_tipi, yayin_kodu, yayin_adi
order by donem, bayi_kodu, mekan_adi, yayin_adi
)
group by donem, mekankodu
当我想在结果表中包含yc/yss
时,我将SELECT
部分安排如下:
select donem, mekankodu, count(yayin_kodu) yc,
SUM(CASE WHEN iade =0 THEN 1 ELSE 0 END) yys,
yc/yys yo
但它给了
ORA-00904 错误:YYS:无效 标识符。
我该怎么办?
【问题讨论】:
【参考方案1】:使用 with 语句:
with subquery_name as
(
select
donem,
mekankodu,
count(yayin_kodu) as yc,
SUM(CASE WHEN iade =0 THEN 1 ELSE 0 END) as yys
from
...
)
select
donem,
mekankodu,
yc,
yys,
yc/yys as yo
from
subquery_name
这是 PL/SQL 的一个非常有用的特性。您正在尝试访问同一查询中生成的列,这是不可能的。一个 with 语句将允许您像在此处所做的那样基于另一个计算列来计算一个新列。
【讨论】:
感谢您的回答。我会试试你的解决方案。 Oracle 是否存在整数数学问题?在我看来,这两个值都是整数,在 SQL Server 中,我将表示除法 (yc/(yys*1.0),以避免四舍五入。 Oracle 不区分整数和其他数字。【参考方案2】:您不能在同一选择中引用其他列。 使用子选择:
select donem, mekankodu, yc, yys, yc/yys yo
from
(
select donem, mekankodu, count(yayin_kodu) yc,
SUM(CASE WHEN iade =0 THEN 1 ELSE 0 END) yys,
yc/yys yo
from ...
) Sub
【讨论】:
【参考方案3】:在 SQL 中你不能访问相邻创建的列,但是你可以访问数据目录:
select donem, mekankodu, count(yayin_kodu) yc,
SUM(CASE WHEN iade =0 THEN 1 ELSE 0 END) yys,
count(yayin_kodu)/SUM(CASE WHEN iade =0 THEN 1 ELSE 0 END) "yc/yys"
from
( select donem,
bayi_adi,
bayi_kodu,
x.mekankodu,
mekan_adi,
mekan_tipi,
yayin_kodu,
yayin_adi,
sum(x.b2b_dagitim + x.b2b_transfer) sevk,
sum(x.b2b_iade) iade,
sum(x.b2b_dagitim + x.b2b_transfer - x.b2b_iade) satis
from mps_view2 x
where x.donem = '200910'
and x.yayin_kodu in (93,95,98,99,103,174,307,309,311,489,491,495,533,534,538,605,641,642,650,2539,
2697,4560,5049,5772,5950,5980,7318,7440,8086,8524,11161,12707,12708,12709,14376,
15107,15309,15633)
and x.mekankodu in (31851,38569,7123,7403,7481)
group by donem, bayi_adi, bayi_kodu, mekankodu, mekan_adi, mekan_tipi, yayin_kodu, yayin_adi
order by donem, bayi_kodu, mekan_adi, yayin_adi
)
group by donem, mekankodu
注意:这并不像看起来那样效率低下……SQL 足够聪明,可以在大多数情况下进行一次计算并使用两次结果。通常情况下,请相信优化器。
【讨论】:
【参考方案4】:你忘了“as”吗?
select donem, mekankodu, count(yayin_kodu) yc,
SUM(CASE WHEN iade =0 THEN 1 ELSE 0 END) AS yys
【讨论】:
AS 在这里是可选的。当我将 AS 添加到所有 SELECT 语句时,它仍然给出相同的错误。一定有别的东西。另外,我写的第一个代码是没有AS的,它可以工作。以上是关于我无法在我的 SQL 代码中计算除法的主要内容,如果未能解决你的问题,请参考以下文章