SELECT t.trade_id,
t.share_holder_id,
t.broker_id,
t.share_amount
FROM trades t
INNER JOIN share_holders sh
ON t.share_holder_id = sh.share_holder_id
INNER JOIN share_holder_shares shs
ON shs.share_holder_id = sh.share_holder_id
WHERE (t.share_amount >50000
AND shs.amount <0
OR t.transaction_type = 2)
GROUP BY t.trade_id,
t.share_holder_id,
t.broker_id,
t.share_amount
HAVING t.share_amount =
(SELECT SUM(DECODE(transaction_type,1,share_amount))
FROM trades t1
WHERE t.share_id = t1.share_id
AND t.share_holder_id = t1.share_holder_id
AND t.transaction_time < t1.transaction_time
GROUP BY t.share_amount
)
OR t.share_amount =
(SELECT SUM(DECODE(transaction_type,2,0-share_amount))
FROM trades t1
WHERE t.share_id = t1.share_id
AND t.share_holder_id = t1.share_holder_id
AND t.transaction_time < t1.transaction_time
GROUP BY t.share_amount
)
ORDER BY t.trade_id,
t.share_holder_id,
t.broker_id ;
我在第二个子查询中错误地获取了一个组。不明白如何解决它。该查询的目的是找到允许股东每笔交易买入或卖出超过50,000股的所有经纪人,或出售他们没有拥有的股票。
答案 0 :(得分:0)
以下是您的having
子查询之一:
(SELECT SUM(DECODE(transaction_type,1,share_amount))
FROM trades t1
WHERE t.share_id = t1.share_id
AND t.share_holder_id = t1.share_holder_id
AND t.transaction_time < t1.transaction_time
GROUP BY t.share_amount
)
在<{em> having
之后处理group by
子句。因此,在having
子句中,您可以使用用于聚合的列(t.trade_id
,t.share_holder_id
,t.broker_id
,t.share_amount
)或聚合函数中的其他列(例如max(t.share_id)
)。
我注意到您正在与用于聚合的列进行比较。您可以通过将逻辑移动到where
子句(group by
之前)来修复语法错误。这解决了语法问题;我不确定这是否是你要找的结果。