MySQL查询以最新日期计数重复次数

时间:2019-03-02 16:55:12

标签: mysql

我有下表:

 client  datescanned  owa
 user1    2019-02-27   A1
 user1    2019-02-28   A3
 user1    2019-02-29   A6
 user1    2019-02-29   A2
 user1    2019-02-29   A1

这是我的查询

 SELECT COUNT(*) FROM s1 WHERE OWA= "A1" AND CLIENT ='user1' and 'datescanned' = 
 ( SELECT max('datescanned') FROM s1)

基本上我只想知道最近日期(2019-02-29)的A1计数。在这种情况下,它应该返回1,现在返回2(从2019-02-27选择A1。

任何帮助将不胜感激!

谢谢 娜塔莉(Nathalie)

**更新1 **

现在,除了...以下工作正常

SELECT COUNT(*) 
FROM s1
WHERE trim(OWA)= "A1" 
AND trim(CLIENT) ='user1' 
AND datescanned  =  ( SELECT max(datescanned) FROM s1 where trim(OWA) 
='A1')

更新表

 client  datescanned  owa
 user1    2019-02-27   A1
 user1    2019-02-28   A3
 user1    2019-02-29   A1
 user1    2019-02-29   A1
 user1    2019-02-30   A0
 user1    2019-02-30   A3

如果没有最新日期为2019-02-30的A1,它会给我“ 2”,因为2019-02-29中有两个A1 ...

我希望该值为零,因为仅最新日期没有A1。

1 个答案:

答案 0 :(得分:1)

只需删除列名周围的单引号

 SELECT COUNT(*) 
 FROM s1 
 WHERE trim(OWA)= "A1" 
 AND trim(CLIENT) ='user1' 
 AND datescanned  =  ( SELECT max(datescanned) FROM s1) 

如果使用单引号,则引用的是字符串文字而不是列名..
当您需要引用复合列名或保留字时,可以使用反引号

您是否可以基于无效日期进行查询(2019 02 29(也尝试选择A3(2019-02-28)

 SELECT COUNT(*) 
 FROM s1 
 WHERE trim(OWA)= "A3" 
 AND trim(CLIENT) ='user1' 
 AND datescanned  =  ( SELECT max(datescanned) FROM s1 where trim(OWA) ='A3')

当然可以简单地从s1中选择max(datescanned)并检查实际结果

并最终尝试使用like代替=

 SELECT COUNT(*) 
 FROM s1 
 WHERE trim(OWA) like "A3" 
 AND trim(CLIENT) like 'user1' 
 AND datescanned  =  ( SELECT max(datescanned) FROM s1 where trim(OWA) ='A3')