比如查询最近一周的销售数量2012-12-01 2000
2012-12-01 100
2012-12-02 50
2012-12-10 2000
2012-12-11 1000
2012-12-11 2000
2012-12-11 3000
2012-12-12 2000
2012-12-12 2000
2012-12-13 5000
2012-12-13 6000
2012-12-15 1000
2012-12-15 2500
2012-12-16 1500
2012-12-16 2000
2012-12-16 3500
2012-12-17 6000
2012-12-17 5500查询出来要这样的
最近一周
2012-12-18 0
2012-12-17 11500
2012-12-16 7000
2012-12-15 3500
2012-12-14 0
2012-12-13 11000
2012-12-12 4000
最近一个月同理,哪天没有的也要显示日期 ,数量是0
2012-12-01 100
2012-12-02 50
2012-12-10 2000
2012-12-11 1000
2012-12-11 2000
2012-12-11 3000
2012-12-12 2000
2012-12-12 2000
2012-12-13 5000
2012-12-13 6000
2012-12-15 1000
2012-12-15 2500
2012-12-16 1500
2012-12-16 2000
2012-12-16 3500
2012-12-17 6000
2012-12-17 5500查询出来要这样的
最近一周
2012-12-18 0
2012-12-17 11500
2012-12-16 7000
2012-12-15 3500
2012-12-14 0
2012-12-13 11000
2012-12-12 4000
最近一个月同理,哪天没有的也要显示日期 ,数量是0
-- Author :TravyLee(物是人非事事休,欲语泪先流!)
-- Date :2012-12-18 09:54:22
-- Version:-- Microsoft SQL Server 2012 - 11.0.2100.60 (Intel X86) -- Feb 10 2012 19:13:17 -- Copyright (c) Microsoft Corporation-- Enterprise Edition: Core-based Licensing on Windows NT 6.1 <X86> (Build 7601: Service Pack 1)--
----------------------------------------------------------------
--> 测试数据:[test]
if object_id('[test]') is not null drop table [test]
go
create table [test]([dt] datetime,[sl] int)
insert [test]
select '2012-12-01',2000 union all
select '2012-12-01',100 union all
select '2012-12-02',50 union all
select '2012-12-10',2000 union all
select '2012-12-11',1000 union all
select '2012-12-11',2000 union all
select '2012-12-11',3000 union all
select '2012-12-12',2000 union all
select '2012-12-12',2000 union all
select '2012-12-13',5000 union all
select '2012-12-13',6000 union all
select '2012-12-15',1000 union all
select '2012-12-15',2500 union all
select '2012-12-16',1500 union all
select '2012-12-16',2000 union all
select '2012-12-16',3500 union all
select '2012-12-17',6000 union all
select '2012-12-17',5500
go--首先构建最近一周的日期:
with t(dt)
as
(
select
dt=convert(varchar(10),dateadd(dd,-number,getdate()),120)
from
master..spt_values
where
number between 0 and 6
and type='p'
)
--用这个表的日期跟原数据表左连接
select
t.dt,
sum(isnull(a.sl,0)) as sl
from
t
left join
test a
on
t.dt=convert(varchar(10),a.dt,120)
group by
t.dt
/*
dt sl
------------------------------------
2012-12-12 4000
2012-12-13 11000
2012-12-14 0
2012-12-15 3500
2012-12-16 7000
2012-12-17 11500
2012-12-18 0
*/
as
(dt)什么意思
;with 名字(字段名字) as(查询语句)--这个是公用表达式 那个(dt)就是给查询出来的那个列取得名字