SQL分组的问题

来源:百度知道 编辑:UC知道 时间:2024/06/23 12:55:33
表如下。

A B C D F
1 18 16 2004-01-02 18:00:05
1 10 4 2004-01-02 18:00:01
1 10 4 2004-01-03 18:00:05
2 18 16 2004-01-02 18:00:05
3 9 4 2004-01-01 18:00:01
3 9 3 2004-01-02 18:00:01
2 10 5 2004-01-01 18:00:01

分组查出D< 2004-01-03 且B>C且D最大 ,如果D相同就查出F最大的.
能得出如下:

1 18 16 2004-01-02 18:00:05
2 18 16 2004-01-02 18:00:05
3 9 3 2004-01-02 18:00:01
A字段 1
B字段 18
C字段 16
D字段 2004-01-02
F字段 18:00:05

实际上是一个集合的问题

D< 2004-01-03 且B>C且D最大
条件简化 max(D) D in (D< 2004-01-03) and B > C
那么查询就是:
select A1.A,A1.B,A1.C,A1.D,A1.F from test A1 where A1.D in (select max(A2.D) from test A2 where D < to_date('2004-01-03','yyyy-mm-dd')) and B>C;
-----------4条记录
A B C D F
1 18 16 2004-01-02 18:00:05
2 18 16 2004-01-02 18:00:05
3 9 3 2004-01-02 18:00:01

如果D相同就查出F最大的,条件就是F in max(F) where F在上面的这个表里面
,注意光查询F的约束的条件不够,另外一个隐藏条件就是匹配这个F的别的字段也都在上面这个结果集合中;
那么语句就是
select A1.A,A1.B,A1.C,A1.D,A1.F from test A1 where A1.D in (select max(A2.D) from test A2 where D < to_date('2004-01-03','yyyy-mm-dd')) and B>C and A1.F in (select max(A3.F) from (select A1.A,A1.B,A1.C,A1.D,A1.F from test A1 where A1.D in (select max(A2.D) from test A2 where D < to_date('2004-01-03','yyyy-mm-dd')) and B>C) A3);

-----------2条记录
A B C D