+ -
当前位置:首页 → 问答吧 → 搜了半天也没搜到,一年十二个月,获取最近三个月的数据。。。

搜了半天也没搜到,一年十二个月,获取最近三个月的数据。。。

时间:2011-11-24

来源:互联网

这个语句怎么写,
1到12个月根据日期判断获取前三个月的数据,
比如这个月是11月,那我就要获取 9.10.11 如果下个月是12 月 那我就要 10.11.12的数据 依次类推,谢谢

作者: tianyazaixian   发布时间: 2011-11-24

where datediff(month,[date],getdate)<2

作者: ssp2009   发布时间: 2011-11-24

datediff(month,dt,getdate())<=3

作者: sql_sf   发布时间: 2011-11-24

where datediff(mm,[你的日期列],getdate()) <=2

作者: AcHerat   发布时间: 2011-11-24

引用 2 楼 sql_sf 的回复:
datediff(month,dt,getdate())<=3


作者: fredrickhu   发布时间: 2011-11-24

引用 4 楼 fredrickhu 的回复:

引用 2 楼 sql_sf 的回复:
datediff(month,dt,getdate())<=3

datadiff是两个日期的月差,我这边只会输入一个本月的日期,这样求出来的差是0,几乎所有的都是0,怎么弄啊 

作者: tianyazaixian   发布时间: 2011-11-24

测试数据:create database test1
create table test1(id int ,sj int)
insert into test 
select 1,2 union all
select 2,2 union all
select 3,3 union all
select 4,4 union all
select 5,5 union all
select 6,6 union all
在这些数据中,获得4,5,6 月的
insert into test 
select 1,2 union all
select 2,2 union all
select 3,3 union all
select 4,4 union all
select 5,5 union all
select 6,6 union all
select 7,7
就获取5,6,7 月
这之间会输入一个日期
drop table test1;
drop database test1

作者: tianyazaixian   发布时间: 2011-11-24

where datediff(mm,[你的日期列],你传入的参数日期) <= 2

作者: AcHerat   发布时间: 2011-11-24

引用 4 楼 fredrickhu 的回复:
引用 2 楼 sql_sf 的回复:
datediff(month,dt,getdate())<=3
 

+1

作者: liuqian4243   发布时间: 2011-11-24

where 7-sj between 0 and 2

作者: AcHerat   发布时间: 2011-11-24

引用 7 楼 acherat 的回复:
where datediff(mm,[你的日期列],你传入的参数日期) <= 2


作者: fredrickhu   发布时间: 2011-11-24

引用 6 楼 tianyazaixian 的回复:

测试数据:create database test1
create table test1(id int ,sj int)
insert into test
select 1,2 union all
select 2,2 union all
select 3,3 union all
select 4,4 union all
select 5,5 union all
select……

非日期類型?

作者: roy_88   发布时间: 2011-11-24

引用 2 楼 sql_sf 的回复:

datediff(month,dt,getdate())<=3

dt 是那个字段?谢谢

作者: tianyazaixian   发布时间: 2011-11-24

日期這樣用
SQL code
DECLARE @dt DATETIME
SET @dt='2011-11-01'
SELECT * FROM test1 AS a WHERE NOT EXISTS(SELECT 1 FROM test1 WHERE DATEDIFF(m,sj,@dt)<3

作者: roy_88   发布时间: 2011-11-24

改改

SQL code
DECLARE @dt DATETIME
SET @dt='2011-11-01'
SELECT * FROM test1 AS WHERE DATEDIFF(m,sj,@dt)<3

--取表的最后3個月
DECLARE @dt DATETIME
SELECT @dt=MAX(sj) FROM test1
SELECT * FROM test1 AS a  WHERE DATEDIFF(m,sj,@dt)<3

作者: roy_88   发布时间: 2011-11-24

按樓主的數據


SQL code
SELECT a.* 
FROM test AS a
    INNER JOIN (SELECT MAX(sj) AS sj FROM test) AS b ON a.sj>b.sj-3

作者: roy_88   发布时间: 2011-11-24

SQL code

select * from tb where dt between convert(varchar(7),dateadd(mm,-2,getdate()),120)+'-01' and getdate()


作者: pengxuan   发布时间: 2011-11-24