SQL-获取与上个月相比的差异摘要

问题描述

我有一个与此表类似的表:

| 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,但我对其他平台(如果有)之间的差异感兴趣。

谢谢

解决方法

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

一个选项使用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
,

您可以使用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