如何从其中value1和value2字段忽略value2字段的表中获取value1的最大值

时间:2019-06-21 05:39:59

标签: mysql sql

我有一个表,其中column1 =日期,column2 = A / B,column3 = id。我想要结果中与ID相比较的最新日期应该是列2中的B,忽略A

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn" name="SocketServerLog" monitorInterval="30">
  <Appenders>
    <RollingRandomAccessFile name="RollingRandomAccessFile" fileName="logs/info.log"
                 filePattern="logs/$${date:yyyy-MM}/info-%d{yyyy-MM-dd-HH}-%i.log.gz">
      <PatternLayout>
        <Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
      </PatternLayout>
      <Policies>
        <TimeBasedTriggeringPolicy interval="6" modulate="true"/>
        <SizeBasedTriggeringPolicy size="25 MB"/>
      </Policies>
    </RollingRandomAccessFile>
  </Appenders>
  <Loggers>
    <Root level="info">
      <AppenderRef ref="RollingRandomAccessFile"/>
    </Root>
  </Loggers>
</Configuration>

预期结果

C1        C2    C3
10/6/19   A      1
12/6/19   B      1
13/6/19   A      2
09/6/19   A      3
03/6/19   B      1
04/6/19   B      2
12/6/19   B      4
03/6/19   A      5
06/6/19   B      3

3 个答案:

答案 0 :(得分:1)

使用相关子查询

DEMO

select * from t1 a
where c1 =(select max(c1) from t1 b where a.c3=b.c3 )
and c2='B'

输出:

c1         c2   c3
2012-06-19  B   1
2012-06-19  B   4

答案 1 :(得分:0)

假设c1列为有效日期,您可以尝试对max(c1)使用子查询

select  * 
from my_table m 
inner join  (
  select  id,  max(c1) max_c1 
  from my_table  
  group by id  
) t on t.max_c1 = m.c1 and m.c2='A' and t.id = m.id

或者,如果您还需要与ID不匹配的ID,可以附加uisng UNION

select  * 
from my_table m 
inner join  (
  select  id,  max(c1) max_c1 
  from my_table  
  group by id  
) t on t.max_c1 = m.c1 and m.c2='A'
select  * 
from my_table m 
inner join  (
  select  id,  max(c1) max_c1 
  from my_table  
  group by id  
) t on t.max_c1 = m.c1 and m.c2='A' and t.id = m.id 

union 

select  max(c1), c2, id
  from my_table where id not in (
  select id 
  from my_table m 
  inner join  (
    select  id,  max(c1) max_c1 
    from my_table  
    group by id  
  ) t on t.max_c1 = m.c1 and m.c2='A'
select  * 
  from my_table m 
  inner join  (
    select  id,  max(c1) max_c1 
    from my_table  
    group by id  
  ) t on t.max_c1 = m.c1 and m.c2='A' and t.id = m.id 
)
group by c2, id

答案 2 :(得分:0)

如果只希望将c3值与指标一起使用,则可以使用聚合:

select c3,
       (case when group_concat(c2 order by c1 desc) like 'B,%'
             then 'Valid'
             else 'Invalid'
        end) as flag
from t
group by c3;