Sql Server : How to use an aggregate function like MAX in a WHERE clause

前端 未结 6 1168
灰色年华
灰色年华 2020-12-03 04:48

I want get the maximum value for this record. Please help me:

SELECT rest.field1 
    FROM mastertable AS m
    INNER JOIN  (
        SELECT t1.field1 field1         


        
6条回答
  •  一整个雨季
    2020-12-03 05:22

    The correct way to use max in the having clause is by performing a self join first:

    select t1.a, t1.b, t1.c
    from table1 t1
    join table1 t1_max
      on t1.id = t1_max.id
    group by t1.a, t1.b, t1.c
    having t1.date = max(t1_max.date)
    

    The following is how you would join with a subquery:

    select t1.a, t1.b, t1.c
    from table1 t1
    where t1.date = (select max(t1_max.date)
                     from table1 t1_max
                     where t1.id = t1_max.id)
    

    Be sure to create a single dataset before using an aggregate when dealing with a multi-table join:

    select t1.id, t1.date, t1.a, t1.b, t1.c
    into #dataset
    from table1 t1
    join table2 t2
      on t1.id = t2.id
    join table2 t3
      on t1.id = t3.id
    
    
    select a, b, c
    from #dataset d
    join #dataset d_max
      on d.id = d_max.id
    having d.date = max(d_max.date)
    group by a, b, c
    

    Sub query version:

    select t1.id, t1.date, t1.a, t1.b, t1.c
    into #dataset
    from table1 t1
    join table2 t2
      on t1.id = t2.id
    join table2 t3
      on t1.id = t3.id
    
    
    select a, b, c
    from #dataset d
    where d.date = (select max(d_max.date)
                    from #dataset d_max
                    where d.id = d_max.id)
    

提交回复
热议问题