【问题标题】:Find not possible combinations of rows & columns查找不可能的行和列组合
【发布时间】:2021-02-17 14:19:06
【问题描述】:

基于 SQL Server,我有多行多列。每行包含一个产品配置,该配置至少在一列中不同。现在我需要知道哪些是不存在的配置。三列只是为了便于理解的示例。

数据示例:

Product Size Color
Shirt S Red
Shirt S Blue
Shirt S Black
Shirt M Red
Shirt M Blue
Shirt L Yellow

因此,这些配置丢失了:

Product Size Color
Shirt S Yellow
Shirt M Black
Shirt M Yellow
Shirt L Red
Shirt L Blue
Shirt L Black

【问题讨论】:

    标签: sql sql-server


    【解决方案1】:

    您可以使用cross join 生成所有行。然后过滤掉那些存在的:

    select p.product, s.size, c.color
    from (select distinct product from t) p cross join
         (select distinct size from t) s cross join
         (select distinct color from t) c left join
         t
         on p.product = t.product and
            s.size = t.size and
            c.color = t.color
    where t.product is null;
    

    【讨论】:

      【解决方案2】:

      Gordon 的回答没有考虑可为空的列,这里有一个:

      select p.product, s.size, c.color
      from (select distinct product from t) p cross join
           (select distinct size from t) s cross join
           (select distinct color from t) c
      except
      select t.product, t.size, t.color
      from t;
      

      如果您有实际的 productsizecolor 表,则使用这些表而不是 select distinct... from t 会更高效

      【讨论】:

      • FWIW:Gordon Linoff 的回答是得到广泛支持的标准 SQL。并非所有 DMBS 都支持EXCEPT
      • 另外我会假设product 不能为NULL,所以它真的没有任何区别。
      • @Kaii 我不相信这是真的,请参阅stackoverflow.com/questions/26060151/…
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-20
      • 1970-01-01
      • 2023-04-07
      • 1970-01-01
      • 2011-05-20
      相关资源
      最近更新 更多