日期:2014-05-19  浏览次数:20369 次

sql查询请教~
假设有这么一个表A:
id         time           month       year       day     content
1       2006-1-1           1           2006         1         xxxxx
2       2006-1-2           1           2006         2         xxxxx
3       2006-2-1           2           2006         1         xxxxx
4       2006-2-12         2           2006         12       xxxxx
5       2006-7-21         7           2006         21       xxxxx
——————————————————————

(记录的日期如月份年份,都不一定是连续的)
问题是,我该如何写查询语句才能得到2006年2月份前后发表的记录各2条呢?
需要的结果:
id         time             month         year       day     content
2         2006-1-2           1             2006         2         xxxxx
5         2006-7-21         7             2006         21       xxxxx

------解决方案--------------------
把前一筆和後一筆分別取出,放在一個零時表裡
然後 從這個零時表裡抓取
------解决方案--------------------
declare @a table(id int, time smalldatetime, [month] int, [year] int, [day] int, content varchar(10))
insert @a select 1 , '2006-1-1 ', 1 ,2006, 1 , 'xxxxx '
union all select 2 , '2006-1-2 ', 1 ,2006, 2 , 'xxxxx '
union all select 3 , '2006-2-1 ', 2 ,2006, 1 , 'xxxxx '
union all select 4 , '2006-2-12 ', 2, 2006, 12 , 'xxxxx '
union all select 5 , '2006-7-21 ', 7 ,2006, 21 , 'xxxxx '

select top 1 * from @a where time=all(select max(time) from @a a where [year]=2006 and [month] <2)
union all
select top 1 * from @a where time=all(select min(time) from @a a where [year]=2006 and [month]> 2)
------解决方案--------------------
select * from table_name where convert(char(7),time,21) < '2006-02 '
------解决方案--------------------
先算出前后两个月是几月, 然后分别用> = 和 <=做条件,检索MAX 和MIN

因为不知道是什么库, 所以没写SQL,只能给个思路
------解决方案--------------------
-- 刚刚看错了--
declare @a table(id int, time smalldatetime, [month] int, [year] int, [day] int, content varchar(10))
insert @a select 1 , '2006-1-1 ', 1 ,2006, 1 , 'xxxxx '
union all select 2 , '2006-1-2 ', 1 ,2006, 2 , 'xxxxx '
union all select 3 , '2006-2-1 ', 2 ,2006, 1 , 'xxxxx '
union all select 4 , '2006-2-12 ', 2, 2006, 12 , 'xxxxx '
union all select 5 , '2006-7-21 ', 7 ,2006, 21 , 'xxxxx '


select top 1 * from @a where convert(char(7),[time],21) < '2006-02 ' order by [time] desc
select top 1 * from @a where convert(char(7),[time],21)> '2006-02 ' order by [time]