我正在尝试编写一个SQL查询,显示在一个月内停止订购的STORES。那将是前一个月有订单但当月没有订单的商店。例如,一月份有订单但二月份没有订单的店(这些将停止订购二月份的店)。我想对于一个给定的日期范围内做到这一点的每个月(分组) - @ datefrom- @ dateto停止每月订购的客户-SQL
我与发票#,#STORE和日期列一个表
我想不同的商店将在那里的某个地方。
我正在尝试编写一个SQL查询,显示在一个月内停止订购的STORES。那将是前一个月有订单但当月没有订单的商店。例如,一月份有订单但二月份没有订单的店(这些将停止订购二月份的店)。我想对于一个给定的日期范围内做到这一点的每个月(分组) - @ datefrom- @ dateto停止每月订购的客户-SQL
我与发票#,#STORE和日期列一个表
我想不同的商店将在那里的某个地方。
你可以尝试这样的事情,把它们分解成两个select语句,然后把它们连接起来。
select table1.stores from (select * from table where date = 'January') as table1
left outer join (select * from table where date = 'Feburary') as table2
on table1.invoice= table2.invoice
这将返回一月份的独特的结果,不结果从二月
PS相匹配。这不是一个确切的SQL语句,只是一个想法
我有一个例子可能接近你的愿望。您可能需要调整其对您的方便和期望的性能 - 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
你能提供的样本数据和预期的结果? –
结果 - 1月10日2月14日3月7日4月等。我有一个表,发票#,STORE#和日期列 – Chobes
请编辑您的问题并发布样本数据和预期结果。 –