【问题标题】:T-SQL find missing items between two tablesT-SQL 查找两个表之间的缺失项
【发布时间】:2021-04-10 12:31:49
【问题描述】:

我有一个销售表和一个产品表。示例:

Company    Product            Product
Company1   A                  A
Company1   B                  B
Company2   B                  C
                              D 

公司 1 购买了产品 A 和 B。公司 2 购买了产品 B。

我需要一个 T-SQL 查询来按公司告诉我他们没有购买了哪些产品。最终用户想接触这些公司,看看他们是否有兴趣购买“缺失”的产品,因此我们需要知道与每个客户讨论哪些产品:

我想为所有公司生成一份报告,因此运行查询并提供一个公司 ID 是不够的。我们需要按公司对结果进行分组:

Company1: C, D   (I don't need comma-delimited list; I'm just listing the values as an example)
Company2: A, C, D

【问题讨论】:

    标签: sql-server tsql


    【解决方案1】:

    以下简单的方法可以为您提供有问题的产品:

    select distinct s.company, p.product
    from sales s
    outer apply (
        select product
        from products
        where product not in (select product from sales s2 where s2.company=s.company)
    )p
    

    【讨论】:

      猜你喜欢
      • 2015-05-01
      • 1970-01-01
      • 2011-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多