从sql

时间:2017-12-20 08:41:32

标签: mysql sql greatest-n-per-group

我在sql表中有三列,看起来像TYPE |注册NR。 |名为“cars”的表中的ID。 在TYPE栏中,车辆型号为BMW,MERCEDES等,在REGISTRATION NR。是注册号AB77TRR,UTYIE77等,在ID中,顾名思义,ID为12,13,14等。 问题是,对于同一模型,ID列中可以有多个id,并且注册如下:

BMW AB77TRR 12  
BMW AB77TRR 13  
BMW AB77TRR 14

大多数列只有一个id,但有一些列有更多id,我想只选择最后一个注册,我不能使用LIMIT 1或TOP 1.

如果我运行此选择“选择类型,注册号码,来自汽车的ID(bmw,mercedes,audi,porsche)”,它会显示表ID中的所有记录,我只想告诉我最后的身份证。 例如,如果我运行此选择“选择类型,注册nr。,来自汽车的id(bmw,mercedes)”它将显示:

BMW      AB77TRR 12  
BMW      AB77TRR 13  
BMW      AB77TRR 14   
MERCEDES UTYIE77 11

我想看起来像:

BMW      AB77TRR 14 
MERCEDES UTYIE77 11 

提前谢谢。

2 个答案:

答案 0 :(得分:3)

您应该通过示例了解SQL SELECT type, registration, MAX(id) FROM cars GROUP BY type, registration 基础知识,无论如何这是聚合函数MAX的经典案例:

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // @formatter:off
        http
            .authorizeRequests()
                .antMatchers("/console/**", "/reset").permitAll()
            .and()
                .formLogin()
                .loginPage("/login")
                .permitAll()
            .and()
                .requestMatchers()
                .antMatchers("/login", "/oauth/authorize", "/oauth/confirm_access", "/reset")
            .and()
                .authorizeRequests()
                .anyRequest()
                .authenticated();
        // @formatter:on
    }

答案 1 :(得分:1)

有一个子查询来返回每个类型的最大ID。加入该结果:

select c1.*
from carstable c1
join (select TYPE, max(id) as maxid
      from carstable 
      group by type) as c2
  on c1.TYPE = c2.TYPE and c1.id = c2.maxid
相关问题