如何计算两个日期之间表中列的百分比

时间:2017-01-17 07:06:34

标签: mysql

我使用以下查询显示画布列的百分比,此查询选择所有行并计算百分比,

SELECT ma.canvas, COUNT(1) AS total, COUNT(1) / t.cnt * 100 AS `percentage` FROM tbl_mytable ma  CROSS JOIN (SELECT COUNT(1) AS cnt FROM tbl_mytable ) t  group by ma.canvas

我想计算两个日期之间的百分比,我的表格中有一个名为ptime的列存储时间。

我试过了

SELECT ma.canvas,ma.ptime, COUNT(1) AS total, COUNT(1) / t.cnt * 100 AS `percentage` FROM tbl_mytable ma CROSS JOIN (SELECT COUNT(1) AS cnt FROM tbl_mytable ) t on ptime>='01-13-2017' and ptime<='01-15-2017' group by ma.canvas 

以及

SELECT ma.canvas,ma.ptime, COUNT(1) AS total, COUNT(1) / t.cnt * 100 AS `percentage` FROM tbl_mytable ma CROSS JOIN (SELECT COUNT(1) AS cnt FROM tbl_mytable ) t where ptime>='01-13-2017' and ptime<='01-15-2017' group by ma.canvas 

但都显示空表

请帮助解决这个问题

1 个答案:

答案 0 :(得分:0)

  

这是因为时间以2017-01-17的格式存储,但我以不同的格式查询01-15-2017

在where子句中使用STR_TO_DATE

SELECT 
    ma.canvas,
    ma.ptime, 
    COUNT(1) AS total, 
    COUNT(1) / t.cnt * 100 AS `percentage` 
FROM tbl_mytable ma 
CROSS JOIN (
    SELECT COUNT(1) AS cnt FROM tbl_mytable 
) t 
WHERE ptime >= STR_TO_DATE('01-13-2017', '%d-%m-%Y')
and ptime <= STR_TO_DATE('01-15-2017', '%d-%m-%Y') 
group by ma.canvas

请注意,结果ma.ptime的格式仍为%Y-%m-%d %h:%i:%s。您可以使用DATE_FORMAT格式化结果。