我有一个表iminvbin_sql ..这个表有item_no,loc,bin_no列。每个物品编号在位置2应该有4个箱子。如何找到在loc 2中没有这四个箱子的所有物品?
我试过
select item_no from iminvbin_sql where bin_no not in('910SHIP','910STAGE','910PROD','1') AND loc = 2
但这没有用。
itemno loc bin
0 2 1
0 2 910PROD
0 2 910SHIP
0 2 910STAGE
答案 0 :(得分:1)
我认为这就是你想要的:
select item_no
from iminvbin_sql
where bin_no in ('910SHIP', '901STAGE', '910PROD', '1') and
loc = 2
group by item_no
having count(distinct bin_no) <> 4;
这将检查所有这四个值是否都在垃圾箱中。如果您想验证这四个值是否在和的箱子中没有其他值,您也可以测试它:
select item_no
from iminvbin_sql
where loc = 2
group by item_no
having count(distinct bin_no) <> 4 or
count(distinct case when bin_no in ('910SHIP', '901STAGE', '910PROD', '1') then bin_no end) <> 4 or
count(*) <> 4;
编辑:
在回应波希米亚的评论时,以下内容应该包含所有未完全填充的项目:
select item_no
from iminvbin_sql
group by item_no
having count(distinct case when loc = 2 then bin_no end) <> 4 or
count(distinct case when loc = 2 then bin_no in ('910SHIP', '901STAGE', '910PROD', '1') then bin_no end) <> 4 or
sum(case when loc = 2 then 1 else 0 end) <> 4;
答案 1 :(得分:1)
使用带有group by
子句的having
来确定所有二进制文件是否不存在:
select item_no
from iminvbin_sql
group by item_no
having sum(case when loc = 2 and bin_no in ('910SHIP','901STAGE','910PROD','1') then 1 end) < 4
此查询的重点是,通过将条件移动到case
,它会找到没有列出任何列表的项目,甚至没有loc = 2
数据的项目。
答案 2 :(得分:0)
SELECT
itemno
FROM
iminvbin_sql
WHERE
loc = 2
GROUP BY
itemno
HAVING
4 <> SUM(CASE WHEN bin IN ('910SHIP','901STAGE','910PROD','1') THEN 1 ELSE 0 END)