WHERE NOT IN 的子查询未按预期过滤数据

Subquery with WHERE NOT IN not filtering data as expected

我有一个独立工作的子查询,但当用作过滤器时似乎什么都不做。

我的数据不包含 NULL。我可以 运行 子查询并获取我期望的客户数(具有 PID 的客户,例如 %CLUSTER%)但是当我 运行 完整查询时,WHERE NOT IN 子句似乎没有过滤掉子查询选择的客户。

SELECT PID, ROUND(SUM(bookings),0) AS Bookings
FROM d_bookings
WHERE GU_Name NOT IN (
    SELECT DISTINCT(GU_NAME)
    FROM d_bookings 
    WHERE PID LIKE '%CLUSTER%'
    AND Sales_Level_1 IN (
    'GLOBAL SERVICE PROVIDER'
    ,'APJC__'
    ,'EMEAR-REGION'
    ,'AMERICAS'
    ,'CORP ADJUSTMENT'
    )
    AND Corp_Bookings = 'Y'
)
GROUP BY PID
ORDER BY Bookings DESC;

结果不应包含任何 PID,例如 %CLUSTER%。在英语中,我想要销售给未购买集群的客户的所有 PID 的总预订量。子查询列出了 DID 购买集群的客户,我试图从结果中排除这些客户。

这是一个示例 table:

DROP TABLE IF EXISTS tmpbook;
CREATE TABLE tmpbook ("FYQ" char(10), "gu_name" char(10),"PID" char(20), "bookings" numeric);
INSERT INTO tmpbook
    VALUES 
        ('FY2019Q1', 'Company1','CLUSTER1',12345.67),
        ('FY2019Q1', 'Company1','SOMETHINGELSE',2345.67),
        ('FY2019Q1', 'Company2','CLUSTER2',345.67),
        ('FY2019Q1', 'Company2','SOMETHINGELSE',12345.67),
        ('FY2019Q1', 'Company3','SOMETHINGELSE',2345.67),
        ('FY2019Q1', 'Company3','SOMETHINGELSE',345.67) 
;

预期结果将是 NOTACLUSTER 2691.34 (2345.67 + 345.67)

因为只有 Company3 没有购买集群(应排除 Company1 和 Company2 因为他们确实购买了集群。

我最后遇到了两个问题。 1 - 我的数据被搞砸了。 2 - 我的子查询和主查询需要相同的约束。

SELECT PID, ROUND(SUM(BOOKINGS),0) AS BOOKINGS
FROM d_bookings
WHERE GU_Name NOT IN (
    SELECT GU_NAME
    FROM d_bookings
    WHERE PID LIKE '%CLUSTER%'
    AND Sales_Level_1 IN (
    'GLOBAL SERVICE PROVIDER'
    ,'APJC__'
    ,'EMEAR-REGION'
    ,'AMERICAS'
    ,'CORP ADJUSTMENT'
    )
    AND Corp_Bookings = 'Y')
AND Sales_Level_1 IN (
    'GLOBAL SERVICE PROVIDER'
    ,'APJC__'
    ,'EMEAR-REGION'
    ,'AMERICAS'
    ,'CORP ADJUSTMENT'
    )
AND Corp_Bookings = 'Y'
GROUP BY PID
ORDER BY BOOKINGS DESC;

子查询中 WHERE 子句的其余部分可能应该在主查询中:

SELECT PID, ROUND(SUM(bookings),0) AS Bookings
FROM d_bookings
WHERE GU_Name NOT IN (
    SELECT DISTINCT(GU_NAME)
    FROM d_bookings 
    WHERE PID LIKE '%CLUSTER%'
    )
    AND Corp_Bookings = 'Y'
    AND Sales_Level_1 IN (
    'GLOBAL SERVICE PROVIDER'
    ,'APJC__'
    ,'EMEAR-REGION'
    ,'AMERICAS'
    ,'CORP ADJUSTMENT'
)
GROUP BY PID
ORDER BY Bookings DESC;

但如果这是真的,您应该能够用 NOT LIKE 替换子查询,而不是:

SELECT PID, ROUND(SUM(bookings),0) AS Bookings
FROM d_bookings
WHERE PID NOT LIKE '%CLUSTER%'
    AND Corp_Bookings = 'Y'
    AND Sales_Level_1 IN (
    'GLOBAL SERVICE PROVIDER'
    ,'APJC__'
    ,'EMEAR-REGION'
    ,'AMERICAS'
    ,'CORP ADJUSTMENT'
    )
GROUP BY PID
ORDER BY Bookings DESC;

您的查询似乎应该返回空结果。因为条件 WHERE PID LIKE '%CLUSTER%' 对于两种类型的记录都为真。

例如

'Cluster1' LIKE '%CLUSTER%' --is  true

'NotACluster' LIKE '%CLUSTER%' --is  true

因此,如果您只想筛选出 'Cluster1'、'Cluster1' 等记录,则条件应类似于

PID LIKE 'Cluster%'