首页 > 解决方案 > 检查项目是否有数据

问题描述

我有一个包含很多字段的表。

我想做的是查看是否有任何项目缺少某些字段。

数据示例:

+--------+----------+-------+
| 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”的项目

这甚至可能吗?

标签: sqlsql-servercountsubqueryhaving-clause

解决方案


你的数据没有意义。从您的问题的描述来看,您似乎不希望itemno拥有所有 4 optfields。为此,一种方法使用聚合:

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
)

推荐阅读