这样的SQL查询语句该怎么写?

[复制链接]
查看11 | 回复4 | 2007-1-24 14:35:02 | 显示全部楼层 |阅读模式
我有一表A:
ID
编号 年月
------------------------------------------------------------
1
A
200301
2
A
200305
3
B
200302
4
C
200212
5
B
200211
6
B
200307
7
A
200210
8
C
200305
[B].[/B]
[B].[/B]
[B].[/B]
[B].[/B]
[B].[/B]
[B].[/B]
[B].[/B]
[B].[/B]
[B].[/B]
要求返回(表中编号相同的,年月为最大的记录),结果如下:
ID
编号
年月
------------------------------------------------------------
2
A
200305
3
B
200307
8
C
200305
[B].[/B]
[B].[/B]
[B].[/B]
[B].[/B]
[B].[/B]
[B].[/B]
[B].[/B]
[B].[/B]
[B].[/B]
回复

使用道具 举报

千问 | 2007-1-24 14:35:02 | 显示全部楼层
select max(id),编号,max(年月)
from xxx
group by 编号
回复

使用道具 举报

千问 | 2007-1-24 14:35:02 | 显示全部楼层
select id,编号,max(to_date(年月,'yyyymm)
from xxx
group by 编号
回复

使用道具 举报

千问 | 2007-1-24 14:35:02 | 显示全部楼层
SQL> create table test (idnumber(2) , code varchar2(10) , column_date varchar2(100));
Table created.
SQL>
SQL> insert into test values (1 ,'A', '200301');
1 row created.
SQL> insert into test values (2 ,'A', '200305');
1 row created.
SQL> insert into test values (3 ,'B', '200302');
1 row created.
SQL> insert into test values (4 ,'C', '200212');
1 row created.
SQL> insert into test values (5 ,'B', '200211');
1 row created.
SQL> insert into test values (6 ,'B', '200307');
1 row created.
SQL> insert into test values (7 ,'A', '200210');
1 row created.
SQL> insert into test values (8 ,'C', '200305');
1 row created.
SQL> commit;
Commit complete.
SQL> set linesize 1000
SQL> select * from test where (id , code , to_date(column_date,'yyyymm') ) in
2(select id , code, max( to_date(column_date,'yyyymm')) over (partition by code)maxdate
3from test )
4order by id ;
ID CODE COLUMN_DATE
---------- ---------- ------------------------------------------------------------------------------
2 A
200305
6 B
200307
8 C
200305

这可能不是最好的办法,因为它涉及子查询。我从直觉上以为可以使用分析函数,我再找找。楼上的两个帖子会有问题的。一个数据不对,一个会报语法错误。
回复

使用道具 举报

千问 | 2007-1-24 14:35:02 | 显示全部楼层
select * from test where createdate = (select max(b.createdate) from test b where test.serialno=b.serialno)
我在sql server测试达到要求。
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

主题

0

回帖

4882万

积分

论坛元老

Rank: 8Rank: 8

积分
48824836
热门排行