停止订购每月SQL的客户

时间:2015-09-14 02:25:49

标签: sql sql-server

我正在尝试编写一个SQL查询,显示在一个月内停止订购的STORES。那将是前一个月有订单的STORES,但那个月没有订单。例如,1月订单但在2月份没有订单的STORES(这些将是停止订购2月份的商店)。我希望每个月(分组)为给定的日期范围 - @ datefrom- @ dateto

执行此操作

我有一张表有一个INVOICE#,STORE#和一个DATE列

我猜不同的STORE会在某处。

1 个答案:

答案 0 :(得分:0)

我有一个可能接近你想要的例子。您可能需要调整它以方便和期望的性能 - http://sqlfiddle.com/#!3/231c4/15

create table test (
  invoice int identity,
  store int,
  dt date
);

-- let's add some data to show that
-- store 1 ordered in Jan, Feb and Mar
-- store 2 ordered in Jan (missed Feb and Mar)
-- store 3 ordered in Jan and Mar (missed Feb)
insert into test (store, dt) values 
(1, '2015-01-01'),(1, '2015-02-01'),(1, '2015-03-01'),
(2, '2015-01-01'),
(3, '2015-01-01'),                  (3, '2015-03-01');

Query
-----
with 
months as (select distinct year(dt) as yr, month(dt) as mth from test),
stores as (select distinct store from test),
months_stores as (select * from months cross join stores)

select * 
from months_stores ms
left join test t
  on t.store = ms.store
  and year(t.dt) = ms.yr
  and month(t.dt) = ms.mth
where 
  (ms.yr = 2015 and ms.mth between 1 and 3)
  and t.invoice is null

Result:
yr     mth     store   ...other columns
2015   2       2
2015   2       3
2015   3       2

The results show us that store 2 missed orders in months Feb and Mar
and store 3 missed an order in Feb