我想找到所有至少有一个事务被拒绝但不是全部的桶。理想情况下,我希望在单个查询中使用key = bucket_id和value = ids的Map。
id | bucket_id | status
1 | 1 | 'AVAILABLE'
2 | 1 | 'AVAILABLE'
3 | 1 | 'REJECTED'
4 | 2 | 'REJECTED'
5 | 2 | 'REJECTED'
6 | 2 | 'REJECTED'
我目前无效的查询:
SELECT distinct t.bucket_id, t.id
FROM Transaction t
GROUP BY t.bucket_id, t.id
HAVING
EXISTS (select t.id FROM t WHERE t.status=REJECTED)
AND
EXISTS (select t.id FROM t WHERE t.status<>REJECTED)
作为此查询的结果,我得到了桶1和2。
我如何表达条件:&#34;至少一个被拒绝但不是全部&#34;在HAVING条款中?
答案 0 :(得分:1)
distinct
将无法工作GROUP BY
或HAVING
使用WHERE
来代替SELECT distinct t.bucket_id
FROM transac t
WHERE
EXISTS (SELECT T2.id
FROM transac T2
WHERE
T2.status='REJECTED'
AND T2.bucket_id = t.bucket_id)
AND EXISTS (SELECT T2.id
FROM transac T2
WHERE
T2.status<>'REJECTED'
AND T2.bucket_id = t.bucket_id)
修改强>
如果状态只有2个有效值,这是另一个更简单的解决方案。意味着Exists
另一个与您正在寻找的状态不同的transac。
SELECT distinct t.bucket_id
FROM transac t
WHERE
EXISTS (SELECT T2.id
FROM transac T2
WHERE
T2.status <> t.status
AND T2.bucket_id = t.bucket_id)