如何利用oraclesql中的exists进行选择和提取

m2xkgtsf  于 2021-07-24  发布在  Java
关注(0)|答案(2)|浏览(265)

我想选择 type=a 以及 product=1 ```
customer type product
A a 1
A b 1
A c 2
B b 2
B b 1
C c 1
C c 1

因此,我期望的结果如下

customer type product
A a 1
A b 1
A c 2

我想添加选择器 `product = 1` 在下面的示例中。

SELECT t1.customer, t1.type ,t1.product
FROM yourTable t1
WHERE EXISTS (SELECT 1 FROM yourTable t2 WHERE t2.customer = t1.customer AND t2.type = 'a');

因为我是入门级的。如果有人有意见,请告诉我。谢谢
gpnt7bae

gpnt7bae1#

可以将条件添加到子查询:

SELECT t1.customer, t1.type, t1.product
FROM yourTable t1
WHERE EXISTS (SELECT 1
              FROM yourTable t2
              WHERE t2.customer = t1.customer AND
                    t2.type = 'a' AND
                    t2.product = 1
             );

如果您只想要客户:

select customer
from yourtable
group by customer
having sum(case when type = 'a' and product = 1 then 1 else 0 end) > 0;
k3bvogb1

k3bvogb12#

这是您要求的版本

WITH CTE_yourTable AS
(
SELECT CUSTOMER
FROM yourTable
WHERE 
type = 'a' AND
product = 1)
SELECT t1.customer, t1.type, t1.product
FROM yourTable t1
WHERE EXISTS (SELECT 1
              FROM CTE_yourTable t2
              WHERE t2.customer = t1.customer 
             );

相关问题