欢迎您访问新疆栾骏商贸有限公司,公司主营电子五金轴承产品批发业务!
全国咨询热线: 400-8878-609

新闻资讯

技术学院

如何用 SQL 查询在指定时间段内连续多日都有特定商品库存的商店?

作者:心靈之曲2024-10-27 00:00:00

sql 实现思路

如何查询在指定时间段内连续多日都有特定商品库存的商店?以下是一个 sql 实现思路:

通过 union 操作符,把每天库存信息拼接到一起,形成一张临时表:

select 商店 from 表 where 日期='2025-09-01'  -- and 后续可以添加不同的商品信息
union
select 商店 from 表 where 日期='2025-09-02'
union
select 商店 from 表 where 日期='2025-09-03'

然后对临时表进行分组,统计每家商店出现在不同日期的次数:

select 商店,count(distinct 日期) countdate 
from (
    select 商店 from 表 where 日期='2025-09-01'  -- and 后续可以添加不同的商品信息
    union
    select 商店 from 表 where 日期='2025-09-02'
    union
    select 商店 from 表 where 日期='2025-09-03'
) as tab 
group by 商店

最后,筛选出连续多日都有库存的商店:

HAVING countdate=3

这样,就可以查询到在 9 月 1 日、2 日、3 日都有指定商品库存的商店。