sql - 检查项目是否有数据
问题描述
我有一个包含很多字段的表。
我想做的是查看是否有任何项目缺少某些字段。
数据示例:
+--------+----------+-------+
| ITEMNO | OPTFIELD | VALUE |
+--------+----------+-------+
| 0 | x | 1 |
+--------+----------+-------+
| 0 | x | 1 |
+--------+----------+-------+
| 0 | x | 1 |
+--------+----------+-------+
| 0 | x | 1 |
+--------+----------+-------+
| 0 | x | 1 |
+--------+----------+-------+
我想看看是否所有的“ITEMNO”都有 4 个“OPTFIELD”。
所以我想应用的逻辑是这样的:
显示所有没有“OPTFIELD”-“LABEL”、“PG4”、“PLINE”、“BRAND”的项目
这甚至可能吗?
解决方案
你的数据没有意义。从您的问题的描述来看,您似乎不希望itemno
拥有所有 4 optfield
s。为此,一种方法使用聚合:
select itemno
from mytable
where optfield in ('LABEL', 'PG4', 'PLINE', 'BRAND')
group by itemno
having count(*) < 4
另一方面,如果您想展示所有缺失(itemno, optfield)
的元组,那么您可以将 s 列表itemno
与带有 s 的派生表交叉连接optfield
,然后使用not exists
:
select i.itemno, o.optfield
from (select distinct itemno from mytable) i
cross join (values ('LABEL'), ('PG4'), ('PLINE'), ('BRAND')) o(optfield)
where not exists (
select 1
from mytable t
where t.itemno = i.itemno and t.optfield = o.optfield
)
推荐阅读
- c++ - 如何添加成员函数,例如 Boost Log 过滤器?
- mongodb - 更新 mongo db 中的所有记录
- push-notification - 使用 web push sdk showSlideDownPrompt 在 oneSignal 手动提示中添加延迟和 pageViews
- amazon-web-services - 如何将 ssm 参数获取到 yaml 文件?
- installation - 在 /home/username/.local/bin 而不是 /usr/local/bin 中安装气流
- python-3.x - 在迭代产品(行 [1])时收到错误“ConnectionResetError:[WinError 10054] 现有连接被远程主机强制关闭”
- javascript - 如何减去对象值并将结果添加到新属性
- amazon-cloudformation - Cloudformation 模板 - IAM 角色和 Lambda 资源
- javascript - 打字稿:“从不”类型上不存在属性“标签”
- html - 在节点中,我可以使用链接通过快速调用将数据发送到 api 吗?