我有一个以item_Number作为其主键的产品表。每个项目都分配到一个位置,并且每个项目都可以标记为不同的类别。
我想编写一个查询来显示没有类别“小”的item_number。考虑到数据库中有成千上万个项目,需要知道哪些项目以后没有什么小类别。
这里是样本数据集,以供参考和示例
Item_Number Location Category
A East Big
A East Small
A East Medium
B East Big
B East Medium
C East Big
C East Small
C East Medium
D East Big
D East Medium
这是我的初始代码
select item_Num, location
from PRODUCT
WHERE location = 'East' and category <> 'Small'
该代码返回
Item_Number Location
A East
A East
B East
B East
C East
C East
D East
D East
预期结果应该是
Item_Number Location
B East
D East
答案 0 :(得分:2)
您可以使用分组:
SELECT item_Num, 'East'
FROM PRODUCT
WHERE location = 'East'
GROUP BY item_num
HAVING COUNT(CASE WHEN category = 'Small' THEN 1 END) = 0
HAVING
子句就像WHERE
应用于具有相同item_num
的记录的 group 组。该查询的谓词将检查不包含任何category = 'Small'
记录的组。
答案 1 :(得分:0)
使用不存在的相关子查询
select distinct item_Num, location
from PRODUCT a
WHERE location = 'East' and not exists
(select 1 from PRODUCT b where a.item_Num=b.item_Num and b.Category='Small'
and b.location = 'East')
或者您可以尝试这个
select item_Num, location
from product
WHERE location = 'East'
group by item_Num, location
having sum(case when Category='Small' then 1 else 0 end)=0
答案 2 :(得分:0)
不存在
select t1.* from PRODUCT t1
where not exists ( select 1 from PRODUCT t2 where t1.Item_Number=t2.Item_Number and Category='Small')
and location='East'
答案 3 :(得分:0)
请尝试这个。
SELECT DISTINCT item_Num, location
FROM PRODUCT
WHERE location = 'East' and Item_Number Not in (SELECT Item_Number FROM PRODUCT WHERE category ='Small')