【问题标题】:SQL - get summary of differences vs previous monthSQL - 获取与上个月的差异摘要
【发布时间】:2020-12-23 11:48:33
【问题描述】:

我有一张和这张类似的桌子:

| id | store | BOMdate    |
| 1  |  A    | 01/10/2018 |
| 1  |  B    | 01/10/2018 |
| 1  |  C    | 01/10/2018 |
|... |  ...  |    ...     |
| 1  |  A    | 01/11/2018 |
| 1  |  C    | 01/11/2018 |
| 1  |  D    | 01/11/2018 |
|... |  ...  |    ...     |
| 1  |  B    | 01/12/2018 |
| 1  |  C    | 01/12/2018 |
| 1  |  E    | 01/12/2018 |

它包含在 BOM(月初)处于活动状态的商店。

如何查询它以获取当月新开的商店数量 - 上个月不活跃的商店数量?

输出应该是这样的:

| BOMdate    | #newstores |
| 01/10/2018 |     3      | * no stores on previous month
| 01/11/2018 |     1      | * D is the only new active store
| 01/12/2018 |     2      | * store B was not active on November, E is new

我现在如何计算每个商店第一次处于活动状态的时间(嵌套选择,获取 MIN(BOMdate) 然后计数)。但我不知道如何检查每个月与上个月的对比。

我使用 SQL Server,但如果有其他平台的差异,我感兴趣。

谢谢

【问题讨论】:

    标签: sql sql-server subquery window-functions gaps-and-islands


    【解决方案1】:

    我如何查询它以获取当月新开的商店数量 - 上个月不活跃的商店?

    一个选项使用not exists

    select bomdate, count(*) cnt_new_stores
    from mytable t
    where not exists (
        select 1 
        from mytable t1 
        where t1.store = t.store and t1.bomdate = dateadd(month, -1, t.bomdate)
    )
    group by bomdate
    

    你也可以使用窗口函数:

    select bomdate, count(*) cnt_new_stores
    from (
        select t.*, lag(bomdate) over(partition by store order by bomdate) lag_bomdate
        from mytable t
    ) t
    where bomdate <> dateadd(month, 1, lag_bomdate) or lag_bomdate is null
    group by bomdate
    

    【讨论】:

    • 感谢您的回答,我尝试了第一个并像魅力一样工作。我稍后会测试第二个。
    【解决方案2】:

    您可以使用 TSQL 的DATEDIFF 函数将日期与上个月的日期进行比较。

    使用 NOT EXIST 可以计算上个月没有出现的商店,也可以使用 SQL 2017 引入的 TSQL 的STRING_AGG 函数获取列表中的名称。

    select BOMDate, NewStoresCount=count(1),NewStores= STRING_AGG(store,',')  from 
    yourtable
    where not exists
    (
        Select 1 from
        yourtable y where y.store=store and DATEDIFF(m,y.BOMDate,BOMDate)=1
    )
    group by BOMDate
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-18
      • 2012-12-06
      • 2016-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多