sql 不在运算符中
sql not in and in oporators
嗨,我无法过滤仅属于特定列表的资料。
Select material
from price
where region='04'
and pricelist ='5'
and pricelist not in ('4','6','7');
我只想要那些只在价目表 5 中唯一而在任何其他价目表中都没有的材料。我怎样才能得到这个?
您可以尝试这样的操作(或者,您可以进行自连接,但我认为这同样容易理解,甚至更容易理解):
SELECT material
FROM price a
WHERE region = '04'
AND pricelist = '5'
AND NOT EXISTS ( SELECT 1 FROM price b
WHERE b.material = a.material
AND b.region = a.region
AND b.pricelist != a.pricelist )
上面的操作将在 region
'04' 中找到 material
的值,其中 pricelist
是 '5',同时排除那些相同的材料 in同一地区但价目表不同
您当前的查询只会 return 结果 where pricelist = 5
-- not in
语句是不相关的,除非它排除了该记录。听起来您想 return 任何匹配 5 的 material,但没有任何其他非 5 匹配。
一种选择是使用 exist
。这是使用 max
和 case
的条件聚合的另一种选择,它消除了对多个查询的需要:
select material
from (
select material,
max(case when pricelist = '5' then 1 else 0 end) haspl5,
max(case when pricelist != '5' then 1 else 0 end) hasothers
from price
where region='04'
group by material
) t
where haspl5 = 1 and hasothers != 1
嗨,我无法过滤仅属于特定列表的资料。
Select material
from price
where region='04'
and pricelist ='5'
and pricelist not in ('4','6','7');
我只想要那些只在价目表 5 中唯一而在任何其他价目表中都没有的材料。我怎样才能得到这个?
您可以尝试这样的操作(或者,您可以进行自连接,但我认为这同样容易理解,甚至更容易理解):
SELECT material
FROM price a
WHERE region = '04'
AND pricelist = '5'
AND NOT EXISTS ( SELECT 1 FROM price b
WHERE b.material = a.material
AND b.region = a.region
AND b.pricelist != a.pricelist )
上面的操作将在 region
'04' 中找到 material
的值,其中 pricelist
是 '5',同时排除那些相同的材料 in同一地区但价目表不同
您当前的查询只会 return 结果 where pricelist = 5
-- not in
语句是不相关的,除非它排除了该记录。听起来您想 return 任何匹配 5 的 material,但没有任何其他非 5 匹配。
一种选择是使用 exist
。这是使用 max
和 case
的条件聚合的另一种选择,它消除了对多个查询的需要:
select material
from (
select material,
max(case when pricelist = '5' then 1 else 0 end) haspl5,
max(case when pricelist != '5' then 1 else 0 end) hasothers
from price
where region='04'
group by material
) t
where haspl5 = 1 and hasothers != 1