【问题标题】:SQL retrieve inner query valueSQL 检索内部查询值
【发布时间】:2015-08-27 07:24:22
【问题描述】:

我有以下疑问:

select SUM(balvalues) from
(
    select ib.CURBAL as balvalues from invbalances ib join inventory on ib.itemnum = inventory.itemnum and ib.location = inventory.location where inventory.itemnum = 'XMP-3500' and ib.siteid = 'BEDFORD'
    UNION ALL
    SELECT -1 * SUM(QUANTITY) from matrectrans where itemnum = 'XMP-3500' and TRANSDATE >= '16-SEP-99' and tostoreloc = 'CENTRAL'
    UNION ALL
    SELECT -1 * SUM(QUANTITY) from matusetrans where itemnum = 'XMP-3500' and TRANSDATE >= '16-SEP-99' and storeloc = 'CENTRAL'
);

但是我想在外部select (itemnum) 中添加另一列,这样我就可以在join 中使用另一个查询:

select SUM(balvalues), ib.itemnum

我已尝试将 itemnum 添加到每个内部选择,以确保所有 unions 和外部选择的输出列数相同,但我仍然收到此错误:

ORA-00904: "IB"."ITEMNUM": 标识符无效

如何从子查询中获取 itemnum 值?

【问题讨论】:

    标签: sql oracle oracle11g


    【解决方案1】:

    将 itemnum 添加到您的内部和外部查询。将分组依据添加到您的内部查询和外部查询。

    select SUM(balvalues), itemnum from
    (
        select ib.CURBAL as balvalues, inventory.itemnum as itemnum from invbalances ib join inventory on ib.itemnum = inventory.itemnum and ib.location = inventory.location where inventory.itemnum = 'XMP-3500' and ib.siteid = 'BEDFORD'
        UNION ALL
        SELECT -1 * SUM(QUANTITY), itemnum from matrectrans where itemnum = 'XMP-3500' and TRANSDATE >= '16-SEP-99' and tostoreloc = 'CENTRAL' group by itemnum
        UNION ALL
        SELECT -1 * SUM(QUANTITY), itemnum from matusetrans where itemnum = 'XMP-3500' and TRANSDATE >= '16-SEP-99' and storeloc = 'CENTRAL' group by itemnum
    ) group by itemnum;
    

    【讨论】:

    • 我尝试了查询并向所有内部查询添加了一个 group by,但我收到了这个错误:ORA-00979: not a GROUP BY expression
    • 尝试将内部查询更改为SELECT SUM(-1*QUANTITY) as balvalues, itemnum...
    • 现在可以了。我还必须在表达式末尾添加 group by 语句:select SUM(balvalues), itemnum from (...) group by itemnum;
    • 已编辑答案 - 添加了缺失的组。
    【解决方案2】:

    外层select不知道这个列 您还需要将它添加到所有内部选择

    【讨论】:

    • 我这样做了,现在我得到了这个错误:ORA-00937: not a single-group group function
    • 您是否在 SQL 中添加了 group by?
    • 所以你把 groupby 放在我怀疑的地方,现在删除它后它可以工作了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多