我遇到了一个问题,我正在使用之前询问的另一个问题。我不想添加那个问题,所以我只是开始一个新问题。此方案适用于SQL Server 2008。
Order Number Order Line Package Part Number Size Cost Reviewed
0001 1 1 A1 S 22.5 Yes
0001 1 1 B2 M 33.1 Yes
0001 1 1 C3 L 11.2 Yes
0001 1 2 A1 XL 15.0 Yes
0001 1 3 A2 M 12.0 Yes
0001 2 1 D1 S 42.9 Yes
0002 1 1 B4 L 72.5 No
0002 1 2 A7 XXL 66.7 No
0002 2 1 C1 XL 11.8 Yes
0002 2 1 B1 S 22.3 Yes
0003 1 1 A1 L 55.2 Yes
我想选择订单号,订单行和包裹。我必须按部件号,尺寸,成本和是否已审核进行搜索。这个表有大约30,000个订单,所以会有多个结果(这就是我想要的)。我必须排除具有订单行的结果,其中包<>换句话说,如果它有一个包<>,我不想要订单行的实例。 1.订单分为多行,每行可以附加多个包。以下是可正常工作的查询。
SELECT
ORDERNumber,
ORDERLine,
Package
FROM
orders a
WHERE NOT EXISTS (SELECT *
FROM orders AS b
WHERE a.ordernumber = b.ordernumber
AND a.orderline = b.orderline
AND b.Package <> 1)
GROUP BY
ORDERNumber,
ORDERLine,
Package
以上是上述示例查询的结果(正确符合我的要求)......
ORDERNUMBER ORDERLINE PACKAGE
0001 2 1
0002 2 1
0003 1 1
当我尝试添加多个条件时,我遇到了问题。例如......
SELECT
ORDERNumber,
ORDERLine,
Package
FROM
orders a
WHERE (REVIEWED = 'Yes' AND SIZE = 'L') OR (REVIEWED = 'Yes' AND SIZE = 'S')
AND NOT EXISTS (SELECT *
FROM orders AS b
WHERE a.ordernumber = b.ordernumber
AND a.orderline = b.orderline
AND b.Package <> 1)
GROUP BY
ORDERNumber,
ORDERLine,
Package
给我以下结果(不符合我的要求)......
ORDERNUMBER ORDERLINE PACKAGE
0001 1 1
0001 2 1
0002 2 1
0003 1 1
订单号0001,订单行1无效,因为它具有包的2和3值。看起来我的条件顺序有问题吗?我试过玩这些条件,但我没有得到我想要的结果。我知道这可以通过两个单独的查询和一个UNION语句完成,但是有一种方法可以为这种情况只做一个查询的多个条件吗?感谢。
答案 0 :(得分:4)
更改您的查询并在OR
参数之间添加括号:
((REVIEWED = 'Yes' AND SIZE = 'L') OR (REVIEWED = 'Yes' AND SIZE = 'S'))
所以完整查询如下所示:
SELECT
ORDERNumber,
ORDERLine,
Package
FROM
orders a
WHERE ((REVIEWED = 'Yes' AND SIZE = 'L') OR (REVIEWED = 'Yes' AND SIZE = 'S'))
AND NOT EXISTS (SELECT *
FROM orders AS b
WHERE a.ordernumber = b.ordernumber
AND a.orderline = b.orderline
AND b.Package <> 1)
GROUP BY
ORDERNumber,
ORDERLine,
Package
因为您的原始查询首次评估(REVIEWED = 'Yes' AND SIZE = 'L')
,如果未匹配,则评估(REVIEWED = 'Yes' AND SIZE = 'S'))
AND NOT EXISTS (SELECT *
FROM orders AS b
WHERE a.ordernumber = b.ordernumber
AND a.orderline = b.orderline
AND b.Package <> 1)
。正如您所看到的,您的存在语句与第二次检查相关联。