SQL查询中的事务性结果-PostgreSQL

问题描述 投票:0回答:1

我在此查询中发现了这种奇怪的行为:

-- 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。

因此,总而言之,我通过修改查询的部分得到了三个不同的值,据我所知,这些部分不应影响答案。

我确定解决难题后会踢自己,这闻起来像一个愚蠢的错误。

sql postgresql group-by union
1个回答
2
投票

类似,您看到的是由于使用union引起的。这组运算符deduplicates

© www.soinside.com 2019 - 2024. All rights reserved.