我有一个独立运行的子查询,但是当用作过滤器时似乎什么也没做。
我的数据不包含任何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购买集群的客户列表,而我试图从结果中排除这些客户。
这是一个示例表:
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,因为他们DID购买了集群。
答案 0 :(得分:1)
子查询中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;
答案 1 :(得分:1)
您的查询似乎应该为您提供空结果。因为两种记录类型的条件“ WHERE PID LIKE'%CLUSTER%”都为真。
例如
'Cluster1' LIKE '%CLUSTER%' --is true
'NotACluster' LIKE '%CLUSTER%' --is true
因此,如果您只想整理“ Cluster1”,“ Cluster1”等记录,则条件应类似于
PID LIKE 'Cluster%'
答案 2 :(得分:0)
我最终遇到了两个问题。 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;