在Oracle SQL中查找列的MAX

时间:2015-04-19 00:47:08

标签: sql oracle aggregate-functions

我有以下表结构:

Table A (A1, ...) where A1 is PK

Table B (B1, B2, ...) where A.A1 = B.B1 and B2 is PK 

Table C (C1, C2, C3, ...) where C.C1 = B.B2 and C1 is PK

给定A.A1和C.C2,我需要获得C3的MAX()。以下显然不起作用:

select c.c3
from A a join B b on a.A1 = b.B1
         join C c on b.B2 = c.C1
where a.A1 = '123'
  and c.C2 = to_date('01-01-2000', 'mm-dd-yyyy')
  and c.C3 = (
    select max(c3)
    from C
    where c1 = c.C1)

查询没有返回任何内容。但是,当我尝试:

select max(c.c3)
from A a join B b on a.A1 = b.B1
         join C c on b.B2 = c.C1
group by a.A1, c.C2
having a.A1 = '123'
  and c.C2 = to_date('01-01-2000', 'mm-dd-yyyy')

似乎它返回正确的值,但它很慢。有没有办法让它与第一个查询(没有分区)一起工作?

2 个答案:

答案 0 :(得分:1)

您可以尝试WITH子句。

您的查询可能是这样的:

;WITH C AS(
    select c.c3
    from A a join B b on a.A1 = b.B1
             join C c on b.B2 = c.C1
    where a.A1 = '123'
      and c.C2 = to_date('01-01-2000', 'mm-dd-yyyy')
)
SELECT MAX(C3) FROM C

或者简单地说,

select max(cs)
from (
    select c.c3 as cs
    from A a join B b on a.A1 = b.B1
             join C c on b.B2 = c.C1
    where a.A1 = '123'
      and c.C2 = to_date('01-01-2000', 'mm-dd-yyyy')
)

答案 1 :(得分:1)

为什么不在max(c3)使用select

select max(c.c3)
from A a join
     B b
     on a.A1 = b.B1 join
     C c
     on b.B2 = c.C1
where a.A1 = '123' and c.C2 = date '2000-01-01';