具有差异条件的多重计数?

时间:2017-05-31 15:44:09

标签: mysql sql

我有一个表event_tbl,其中包含id,add_date,name,events列; 我想要计算所有行和最新的add_date计数,我怎么能在一个sql语句中得到它?

select count(1) as total
from event_tbl
union
select count(id) as latestCount from event_tbl where add_date=(select max(add_date) 
from event_tbl);

但结果是:

------
total|
------
 5499|
-----
 611 |

效率的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

我建议将其写成:

select count(*) as total, sum(add_date = maxad) as lastestCount
from event_tbl e cross join
     (select max(add_date) as maxad from event_tbl) ee;