sql-从具有公共字段的组中获取不同的记录

xwbd5t1u  于 2021-06-25  发布在  Mysql
关注(0)|答案(3)|浏览(281)

我有一张table:供应商\产品

Product , Supplier, Status
Sugar   , N_Supp,   MAIN
Sugar   , S_Supp,   SUB
Sugar   , E_Supp,   MAIN
Water   , N_Supp,   SUB
Water   , S_Supp,   SUB
Water   , W_Supp,   SUB
Milk    , S_Supp,   MAIN
Milk    , N_Supp,   MAIN
Cream   , N_Supp,   SUB
Cream   , E_Supp,   SUB 
Coffee  , S_Supp,   MAIN 
Coffee  , W_Supp,   SUB
Coffee  , N_Supp,   SUB

我必须得到所有产品只有'分'的地位。我用了这个密码。但是我不能找出我的查询的问题,它有不正确的结果

SELECT DISTINCT
    s.product
FROM supplier_product s
WHERE EXISTS (SELECT
    *
FROM supplier_product
WHERE supplier_product.product = s.product
AND supplier_product.status = 'SUB')

结果应该是:

Product
Water
Cream

如果您遇到此问题或任何链接/建议,请提供帮助。我很高兴知道这件事。谢谢。

flvlnr44

flvlnr441#

select distinct product
from supplier_product
where status = 'SUB'
hrirmatl

hrirmatl2#

你可以用 HAVING 以及 GROUP BY :

SELECT product
FROM supplier_product
GROUP BY product
HAVING
    SUM(CASE WHEN status = 'SUB' THEN 1 ELSE 0 END) > 0
    AND SUM(CASE WHEN status <> 'SUB' THEN 1 ELSE 0 END) = 0

在线演示

x0fgdtte

x0fgdtte3#

使用聚合最容易做到这一点:

select sp.product
from supplier_product sp
group by sp.product
having min(sp.status) = max(sp.status) and   -- the statuses are all the same
       min(sp.status) = 'SUB';               -- the value is 'SUB'

相关问题