【问题标题】:Don't Display NULL value When quantity is greater than 1数量大于 1 时不显示 NULL 值
【发布时间】:2020-12-21 12:43:25
【问题描述】:

我对 sql 很陌生,如果这看起来真的很简单,我很抱歉。

我正在努力详细说明问题,但我不确定要使用正确的功能。

我有一个包含产品 ID 的表格(A 列),如果该产品 ID 有不同的选项(小、中、大或 10 厘米、20 厘米、30 厘米或蓝色、黑绿色等),则会填充另一列 ( b) 列提供属性产品 ID。不幸的是,即使您必须选择一个属性(即您不能说您不想要大小或颜色),该列有时也会提供空值。

我要创建的是一个视图,如果只有 1 个选项(列 b 将始终为 NULL),则显示该行,如果有要显示的选项,则还显示该行(不包括列中的任何 NULL 值B)

这是我正在使用的数据示例,您可以在底部附近看到 1964 和 1980 具有属性 ID,但没有其他 NULL 值,因为 7487 和 7880 同时具有 NULL 和属性 ID。

Products_ID AttributeID
7487
7487 7487-19341
7880 7880-19347
7880
1954
1954 1954-9318
7246
7246 7246-18205
2313
4861
6474
6756
6960
6960 6960-18463
5919
5919 5919-14569
947
2320
2320 2320-3561
7742
3070
3070 3070-17697
7702
1964 1964-2469-2475
2869
2869 2869-14506
1980 1980-2412-5795
6783
6783 6783-18310
7816
1815
1815 1815-1667

这就是我想要展示的内容

Products_ID AttributeID
7487 7487-19341
7880 7880-19347
1954 1954-9318
7246 7246-18205
2313
4861
6474
6756
6960 6960-18463
5919 5919-14569
947
2320 2320-3561
7742
3070 3070-17697
7702
1964 1964-2469-2475
2869 2869-14506
1980 1980-2412-5795
6783 6783-18310
7816
1815 1815-1667

【问题讨论】:

  • 我刚刚意识到这些值不是 NULL 它们是空白的。对不起

标签: sql select view null


【解决方案1】:

如果我理解正确,您只需要 NULL 值,前提是表中没有产品的其他值。如果是这样:

select t.*
from t
where t.attributeid is not null or
      not exists (select 1
                  from t tt2
                  where t2.productid = t.productid and
                        t2.attributeid is not null
                 );

如果每个产品最多有一个非空属性,也可以使用聚合:

select productid, max(attributeid)
from t
group by productid;

【讨论】:

    【解决方案2】:
    SELECT T.*
      FROM [test].[dbo].[Stock] as t
    where t.[product_attribute_combo] <> '' or
          not exists (select 1
                      from [test].[dbo].[Stock] as t2
                      where t2.[products_id] = t.[products_id] and
                            t2.[product_attribute_combo] <> ''
                     );
    GO
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-28
      • 1970-01-01
      • 2020-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多