从数据库中选择特定记录

时间:2015-02-27 04:07:10

标签: sql

我有这样的记录表

2013    1
2013    2
2013    3
2013    4
2013    5
2013    6
2013    7
2013    8
2013    9
2013    10
2013    11
2013    12
2014    1
2014    2
2014    3
2014    4
2014    5
2014    6
2014    7
2014    8
2014    9
2014    10

我想选择所有记录和下一个记录,但我不应该选择2013年1月,2月和3月的前3个记录。

3 个答案:

答案 0 :(得分:1)

select yy, mm from table_name
where not (mm < 4 and yy=(select min(yy) from table_name))
order by yy, mm

答案 1 :(得分:0)

如果您使用的是支持窗口功能的DBMS

WITH C AS (
SELECT RANK() OVER (ORDER BY yy, mm) Rnk
       ,yy
       ,mm
FROM YourTableName
)
SELECT yy, mm FROM C WHERE Rnk >= 3

答案 2 :(得分:0)

1)假设MySQL

MySQL不限制逻辑,

即,这不起作用:

select * from my_table order by year,month asc limit count(*)-3;

虽然我会承认这会很好。以下是使用过程的解决方法:

How can select all records excepting first 3 records?

您也可以通过创建新表和auto_incremented id来实现相同的目标:

CREATE TABLE IF NOT EXISTS temptable (id int not null auto_increment,year char(4) not null,month char(2) not null,primary key(id));
insert into temptable (year,month) select * from primary_table order by year,month;
delete from temptable where id <= 3;
select year,month from temptable;
drop table temptable;

希望这有帮助。

相关问题