可以使用GROUP BY或HAVING改进这个简单的选择吗?

时间:2011-11-26 17:20:01

标签: sql oracle select oracle10g

我有以下参考数据。

STORE_CODE      SUPPLIER_CODE
------          ------
ASDA            A3
ASDA            A2
TESCO           A2
TESCO           A4
ASDA            A4
ASDA            A4
ASDA            A4
ASDA            A4
WAITROSE        A3
ASDA            A4
WAITROSE        A3
ASDA            A3
ASDA            A3
ASDA            A4
SAINSBURY       A2
SAINSBURY       A2
SAINSBURY       A6
TESCO           A6
ASDA            A3
TESCO           A3
TESCO           A3
SAINSBURY       A3
WAITROSE        A5
WAITROSE        A5
WAITROSE        A5
WAITROSE        A4
ALDI            A1
ALDI            A1
ALDI            A1
ALDI            A1
ALDI            A1
ALDI            A1
ALDI            A1
ALDI            A1

我想要做的是显示供应商列表,这些供应商至少有4个与之关联的独特商店。

到目前为止,这就是我所说的:

SELECT 
    distinct stoc.supplier_code as SUPPLIER_CODE    
FROM 
        MYTABLE stoc
WHERE
    (select count(distinct a.store_code) from mytable a where a.supplier_code = stoc.supplier_code) >= 4
;

有没有优化我的select语句? where子句看起来很混乱,我想知道我是否可以使用GROUP BYHAVING来改进它?

非常感谢

1 个答案:

答案 0 :(得分:5)

试试这个:

SELECT COUNT(DISTINCT store_code), supplier_code
FROM myTable
GROUP BY supplier_code
HAVING COUNT(DISTINCT store_code) >= 4
ORDER BY 2