Like for like analysis in SQL 即对所有商店的销售额求和,不包括新开的和关闭的商店

Like for like analysis in SQL i.e. sum the sales of all stores excluding new and closed stores

我想like for likeanalysis in SQL Server。例如,我想 sum up the sales of all the stores with sales>0 在整个时间段内(不包括新店或关闭店的销售额)。有没有简单的方法?

只有 sales of store 1 and 3 应该包括在总和中,因为只有这两家商店在所有三个时期都有销售额。 Store 2应该排除在外,因为它是NEW而不是第一期的运行。 Store 4 应该排除在外,因为它已关闭(不是 period 3 中的 运行)。

此代码应 return 预期结果:

select
period,
sum(sales) as Sum
from
(
 select
 period,
 count(*) over (partition by store) as period_count,
 sales from table1
) data
where data.period_count=3
group by period

在条件:"where data.period_count=3" 中,3 是商店必须存在的所需期间数(因此它不包括新的和关闭的商店)。

以下是使用 CTE 的代码 - 处理给定商店和期间的多个销售记录并显示期间的商店编号:

;with table2 as
(select 
 store, 
 period,
 count(*) over (partition by store) as period_count,
 sum(sale) as sale 
 from table1
 group by store, period)
select
period,
count(store) as StoreNumber,
sum(sale) as Sum
from table2
where 
table2.period_count=(select top 1
count(*) from table2
group by store
order by count(*) desc
)
group by period

你也可以看看这个。我还添加 Max(period)

declare @s table(store int, period int, sales int)

insert into @s values 
(1,1,142),
(1,2,109),
(1,3,126),
(2,2,133),
(2,3,123),
(3,1,114),
(3,2,171),
(3,3,125),
(4,1,199),
(4,2,121)

select store from @s group by store having count(period) > 2

select 
period , MAX(Period), sum(sales)
from @s where 
store in (
select store from @s group by store having count(period) > 2
)
group by period