如何对别名列表sql进行求和

时间:2015-07-31 09:45:14

标签: mysql sql

我有查询sql

select date_format(created_at,'%Y-%m-%d') as date,
(select count(*)  from tb_media where date_format(created_at,'%Y-%m-%d') = date ) as total
from tb_media group by date

结果:

enter image description here

如何总结科隆总数?

5 个答案:

答案 0 :(得分:1)

此查询应该有效:

select sum(a.total) from (
select date_format(created_at,'%Y-%m-%d') as date,
(select count(*)  from tb_media where date_format(created_at,'%Y-%m-%d') = date ) as total
from tb_media group by date) as a

答案 1 :(得分:1)

嗯,您有2个可能的查询。简单的一个(如果你想要总计,你不需要其余的查询):

SELECT COUNT(*) FROM tb_media

不那么简单:

SELECT SUM(t.total)
FROM (select date_format(created_at,'%Y-%m-%d') as date,
(select count(*)  from tb_media where date_format(created_at,'%Y-%m-%d') = date ) as total
from tb_media group by date) AS t;

答案 2 :(得分:1)

如果我了解您的要求,那么您需要根据日期明智地计算记录,并且希望他们的总和在最后,您的created_on列是日期类型。如果它是正确的,那么您可以使用以下查询 -

SELECT IFNULL(DATE_FORMAT(created_at,'%Y-%m-%d'),'Total') AS rep_date, 
COUNT(*) total  FROM tb_media 
GROUP BY created_at WITH ROLLUP;

答案 3 :(得分:1)

你可以尝试这个伴侣:

SELECT
    DATE_FORMAT(created_at, '%Y-%m-%d') AS `date`,
    COUNT(<put_table_key_here>) AS `total`
FROM
    tb_media
GROUP BY
    `date`;  

注意

  • 使用表中的主键或任何键来计算所述记录
  • Atleast,避免在脚本中出现性能时使用子查询

答案 4 :(得分:0)

不确定您想要输出数据的内容或方式,但我最好的猜测是您想要一个列表,其中包含日期和每天的计数以及表格末尾的总和? 如果是这样,这将有效:

(select date_format(created_at,'%Y-%m-%d') as date,count(*) 
from tb_media group by date) 
union
(select 'Total',count(*) from tb_media)

或者如果您只想要所有记录的总和,则查询将是

SELECT COUNT(*) FROM tb_media