Search code examples
sqloracle-databaseselectora-00904

I cannot calculate a division in my SQL code


The following code works without problems:

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

When I want to include yc/yss in my result table, I arrange the SELECT part as follows:

select donem, mekankodu, count(yayin_kodu) yc, 
       SUM(CASE WHEN iade =0 THEN 1 ELSE 0 END) yys,
       yc/yys yo

but it gives

ORA-00904 Error: YYS: Invalid identifier.

What should I do?


Solution

  • Use a with statement:

    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
    

    This is a very useful feature of PL/SQL. You're trying to access a generated column within the same query, which is not possible. A with statement will allow you to calculate a new column based on another calculated column as you are doing here.