加入表和过滤条件

时间:2014-02-01 22:08:31

标签: sql sql-server

我正在寻找有关SQL过滤条件的帮助。基本上我尝试JOIN这两个表并用AND和OR语句过滤条件,但无法得到正确的结果。 让我解释一下我想要做的事情。

我有两个样本表:

Opportunity
OpptID  OpptName
1       a
2       b
3       c

Opportunity_Amount
RecID   BucketID    OpptID  Amount
1       101         1       1000
2       104         1       2000
3       101         2       1000
4       102         2       3000
5       105         1       4000
6       106         1       2000
7       103         2       2000
8       103         3       6000
9       104         3       5000

1)示例一 - 查询...条件如下所示

AND (BucketID = 101 and Amount > 1500)
AND ( (BucketID = 102 and Amount < 4000) OR (BucketID = 103 and Amount > 5000) )        

**Desired Output like this:**
OpptID  OpptName 
2       b           (because it match RecID# 4)
3       c           (because it match RecID# 8)
(However, OpptID# 1 is not in the result because the bucket 101 is less than 1500, and no other bucketIDs matched)

2)查询...条件如下所示

AND (BucketID = 104 and Amount > 1500 OR BucketID = 104 and Amount < 6000) 
AND (BucketID = 102 and Amount > 4000)

**Desired Output like this:**
OpptID  OpptName
1       a       (match RecID# 2 and RecID# 9)
3       c       (match RecID# 2 and RecID# 9)
(Now, Oppt# 2 is not in the result because not match of the conditon)

请帮忙。谢谢!

2 个答案:

答案 0 :(得分:1)

我怀疑你根本不想要join。我想你想要一个带有group by子句的having。您正在寻找符合您任何条件的机会。所以:

select oa.OpptId
from Opportunity_Amount oa
group by oa.OpptId
having sum(case when BucketID = 101 and Amount > 1500 then 1 else 0 end) > 0 or
       sum(case when BucketID = 102 and Amount < 4000 then 1 else 0 end) > 0 or
       sum(case when BucketID = 103 and Amount > 5000 then 1 else 0 end) > 0;

这是一个猜测,我不确定条件是否正确。但是你似乎想要OpptId这三个条件中的任何一个都是真的,那就是having子句的作用。

如果您想要其他字段,只需加入另一个表。

having子句中的每个条件都计算满足每个OpptId条件之一的行数。 > 0只是说该条件至少存在一行。

答案 1 :(得分:1)

ORAND之间似乎存在一些逻辑上的混淆。在两个查询中,您都说AND (BucketID = x ...) AND (BucketID = y ...)。怎么可能呢? BucketID的单个值不能同时为101和102或104和102。试试这些变化:

查询#1:

SELECT o.OpptId, o.OpptName
FROM dbo.Opportunity AS o
WHERE EXISTS
(
  SELECT 1 FROM dbo.Opportunity_Amount
    WHERE OpptId = o.OpptId
    AND
    (
      (BucketID = 101 and Amount > 1500)
      OR
      (BucketID = 102 and Amount < 4000)
      OR
      (BucketID = 103 and Amount > 5000)
    )
);

查询#2:

SELECT o.OpptId, o.OpptName
FROM dbo.Opportunity AS o
WHERE EXISTS
(
  SELECT 1 FROM dbo.Opportunity_Amount
    WHERE OpptId = o.OpptId
    AND
    (
      (BucketID = 104 and Amount > 1500 and Amount < 6000) 
      OR
      (BucketID = 102 and Amount > 4000)
    )
);