我在此查询中发现了这种奇怪的行为:
-- TP4N has stock_class = 'Bond'
select lot.symbol
, round(sum(lot.qty_left), 4) as "Qty"
from ( select symbol
, qty_left
-- , amount
from trade_lot_tbl t01
where t01.symbol not in (select symbol from stock_tbl where stock_class = 'Cash')
and t01.qty_left > 0
and t01.trade_date <= current_date -- only current trades
union
select 'CASH' as symbol
, sum(qty_left) as qty_left
-- , sum(amount) as amount
from trade_lot_tbl t11
where t11.symbol in (select symbol from stock_tbl where stock_class = 'Cash')
and t11.qty_left > 0
and t11.trade_date <= current_date -- only current trades
group by t11.symbol
) lot
group by lot.symbol
order by lot.symbol
;
按原样运行,TP4N的数量为1804.42
运行时未注释两个“数量”行,据我所知,这不会影响结果,但是TP4N的数量= 1815.36。只有一个符号(TP4N)的值已更改,其他所有符号均保持不变。
运行带有整个“联合”语句的注释将TP4N = 1827.17的结果以数量为单位
据我所知,正确答案是1827.17。
因此,总而言之,我通过修改查询的部分获得了三个不同的值,据我所知,这些部分不应影响答案。
我确定解决难题后会踢自己,这闻起来像一个愚蠢的错误。
答案 0 :(得分:3)
就像您看到的一样,是由于使用union
引起的。集合运算符将重复数据删除两个查询返回的结果集。因此,在union
组集中添加或删除列可能会影响最终结果集(默认情况下,添加更多列会降低重复的风险)。
根据经验:除非您要重复数据删除,否则应使用union all
(这也更有效,因为数据库不需要搜索重复项)。 / p>