【问题标题】:Check if Item has Data检查项目是否有数据
【发布时间】:2020-08-21 00:02:37
【问题描述】:

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

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

数据示例:

+--------+----------+-------+
| ITEMNO | OPTFIELD | VALUE |
+--------+----------+-------+
| 0      | x        | 1     |
+--------+----------+-------+
| 0      | x        | 1     |
+--------+----------+-------+
| 0      | x        | 1     |
+--------+----------+-------+
| 0      | x        | 1     |
+--------+----------+-------+
| 0      | x        | 1     |
+--------+----------+-------+

有 4 个“OPTFIELD”,我想看看是否所有“ITEMNO”都有。

所以我想应用的逻辑是这样的:

显示所有没有“OPTFIELD”-“LABEL”、“PG4”、“PLINE”、“BRAND”的项目

这可能吗?

【问题讨论】:

    标签: sql sql-server count subquery having-clause


    【解决方案1】:

    您的数据毫无意义。从您的问题描述来看,您似乎想要 itemno 不具有全部 4 个 optfields。为此,一种方法使用聚合:

    select itemno
    from mytable
    where optfield in ('LABEL', 'PG4', 'PLINE', 'BRAND')
    group by itemno
    having count(*) < 4
    

    另一方面,如果您想展示所有缺失的(itemno, optfield) 元组,则可以将itemnos 的列表与optfields 的派生表交叉连接,然后使用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
    )
    

    【讨论】:

    • 小巴您好,感谢您的回复。该表还有其他“OPTFIELD”,但我想看看它们是否有“LABEL”、“PG4”、“PLINE”、“BRAND”。这些字段本身在理论上是我们 ERP 中的可选文件,并不是“需要”添加到项目中,但在我的场景中,我需要它们,我无法找到一种方法来查看它们是否不存在是否有意义?
    猜你喜欢
    • 2011-01-09
    • 1970-01-01
    • 1970-01-01
    • 2012-07-19
    • 2022-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多