我有下表:
trade_id position_id exit_date
34 1
35 1 2016-01-02
36 2 2016-02-07
37 2 2016-02-06
38 3
39 3
我需要按 position_id
分组并且只选择该组中每个 trade_id 都具有 exit_date
的位置填写。换句话说,每个trade_id
在每个 position_id
内组必须有一个 exit_date
以便被选中。
在上表中,只有一个符合条件的组,即:position_id = 2
我尝试了以下方法:
select position_id from trades
where exit_date is not null
group by position_id
但是即使只有一个交易填写了 exit_date,它也会选择头寸。我只需要填写所有 exit_dates 的头寸
最佳答案
您应该使用 HAVING
和 COUNT
而不是使用 WHERE
,如下所示:
SELECT position_id
FROM trades
GROUP BY position_id
HAVING COUNT(*)=COUNT(exit_date)
COUNT(*)
计算所有行,而 COUNT(exit_date)
计算 exit_date 中具有非
列。因此,NULL
值的行HAVING
仅保留这两个计数彼此相等的 position_id=2
。
关于sql - 选择所有元素都满足条件的组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35357332/