SQL查询以分组方式获取最大值的数据

时间:2018-11-15 14:59:10

标签: sql sql-server tsql

我有下表:

Date         Id    Count
2018-09-01   100   50   
2018-09-01   101   60
2018-09-01   102   55
2018-09-02   103   40
2018-09-02   104   30
2018-09-02   105   20
2018-09-02   106   10
2018-09-03   107   30
2018-09-03   108   70

我想获取具有每个日期的最大ID及其最大ID的count列的行。

结果表:

Date         Id    Count
2018-09-01   102   55   
2018-09-02   106   10
2018-09-03   108   70

要获得此结果,sql查询应该是什么?

谢谢。

3 个答案:

答案 0 :(得分:8)

使用select t.* from t where t.count = (select max(t2.count) form t t2 where t2.date = t.date);

row_number()

答案 1 :(得分:1)

您不希望聚合,而希望进行过滤。

#define MSB 1
#define LSB 0

void out_char(char character, char bit_order){

  uint8_t i = 0;
  RSOUT = 1 ; // MSB
  __delay_ms(10); 
  RSOUT = 0 ; // START
  __delay_us(25);
  for (i = 8; i>0; --i){
      if (bit_order){
        RSOUT = (character & 0x80) ? 1:0;
        character <<= 1;
      } else {
        RSOUT = (character & 0x01);
        character >>= 1;
      }
      __delay_us(25);
  }
  RSOUT = 1 ; // STOP

}

void out_str(char * string, uint8_t len, char bit_order){
  uint8_t i = 0;
  for (i = 0; i< len; i++){
    out_char(string[i], bit_order);
  }
}

out_str("Hello world",11, MSB); // 'H' 0x48 will be '0-1-0-0-1-0-0-0'    
out_str("Hello world",11, LSB); // 'H' 0x48 will be '0-0-0-1-0-0-1-0'

答案 2 :(得分:1)

我认为使用自我连接是一种替代选择:

select t.*
from table t
inner join (select Date, max(t.ID) as DID from table t group by Date) t2
on t.Date = t2.Date and t.ID = t2.DID