【问题标题】:Remove entries based on another table max entry基于另一个表最大条目删除条目
【发布时间】:2020-08-12 20:07:42
【问题描述】:

我有 2 个表,StoreProduct(每个商店出售的产品)和 Sales,每个商店每天的每种产品的销售额。

 _________________        ____________________________________________
|   StoreProduct  |      |                      Sales                 |
-------------------      ----------------------------------------------
|StoreId|ProductId|      |StoreId|ProductId|     Date      | Quantity |
|1      | 1001    |      |1      | 1001    | '2019-04-15'  | 2        |
|1      | 1002    |      |1      | 1002    | '2019-04-15'  | 3        |
|2      | 1001    |      |2      | 1003    | '2019-04-15'  | 1        |
|2      | 1003    |      |1      | 1001    | '2020-04-25'  | 5        |
|2      | 1005    |      |1      | 1002    | '2020-04-25'  | 4        |
-------------------      |2      | 1005    | '2020-04-25'  | 2        |
                         ----------------------------------------------

我的目标是如果产品在过去一年没有售出,就将其从商店中移除。

在此示例中,我将删除条目

StoreId ProductId
2       1001  (never sold)
2       1003  (only sold more than a year ago)

使用左连接很容易找到从未出售过的那些。 但是我如何检查那些从未卖过任何东西的那些和过去一年没有卖过任何东西的那些

【问题讨论】:

    标签: sql sql-server tsql date join


    【解决方案1】:

    你可以使用not exists:

    select sp.*
    from storeproduct sp
    where not exists (select 1
                      from sales s
                      where s.storeid = sp.storeid and s.productid = sp.productid and
                            s.date > dateadd(year, -1, getdate())
                     );
    

    如果你想实际删除行:

    delete sp from storeproduct sp
    where not exists (select 1
                      from sales s
                      where s.storeid = sp.storeid and s.productid = sp.productid and
                            s.date > dateadd(year, -1, getdate())
                     );
    

    【讨论】:

      【解决方案2】:

      你可以使用not exists:

      select sp.*
      from storeProduct sp
      where not exists (
          select 1
          from sales s
          where 
              s.storeId = sp.storeId 
              and s.productId = sp.productId
              and s.date >= datefromparts(year(getdate()) - 1, 1, 1)
              and s.date <  datefromparts(year(getdate()), 1, 1)
      )
      

      这将为您提供来自 salesProduct 的行,其中 sales 中不存在上一个日历年相同的 storeIdproductId 的行(截至今天,这意味着 2019 年)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-06-22
        • 1970-01-01
        • 2012-11-23
        • 2021-10-31
        • 1970-01-01
        • 2012-02-22
        • 1970-01-01
        • 2011-05-09
        相关资源
        最近更新 更多