下面有一个查询,该查询从我的数据库中检索数据,该数据库将所有值相加并除以60以将其转换为小时:
SELECT date(att.`date`) as dtDate,
(select sum(early_leave) from `attendance` where `attendance`.early_leave
> 0 and date(`attendance`.`date`) = date(att.date)) / 60 as EL
FROM `attendance` as att
where date(att.`date`) BETWEEN '2018-08-9' and '2018-08-23'
group by date(att.`date`)
order by date(att.`date`)
它的输出是这样的:
现在,我希望它使用2个小数位进行格式化,所以我这样做:
SELECT date(att.`date`) as dtDate,
(select format(sum(early_leave),2) from `attendance` where `attendance`.early_leave
> 0 and date(`attendance`.`date`) = date(att.date)) / 60 as EL
FROM `attendance` as att
where date(att.`date`) BETWEEN '2018-08-9' and '2018-08-23'
group by date(att.`date`)
order by date(att.`date`)
但是为什么某些输出是这样的:
我期望2018-08-10
上的第二个值为28
,依此类推。有人知道为什么会这样吗?还是我以正确的方式格式化它?
答案 0 :(得分:1)
您需要做add_edge()
作为最后一件事,因为除以60将导致结果中额外的小数位:
Graph
如果您不想显示不需要的小数位,只需加0!
format
例如:
format((select sum(early_leave) from `attendance` where `attendance`.early_leave
> 0 and date(`attendance`.`date`) = date(att.date)) / 60, 2) as EL
输出:
format((select sum(early_leave) from `attendance` where `attendance`.early_leave
> 0 and date(`attendance`.`date`) = date(att.date)) / 60, 2)+0 as EL
答案 1 :(得分:1)
将所有值相加并将其除以60,将其转换为小时数
您确定要除以60以将其转换为小时吗?假设early_leave
以分钟为单位存储。是这样吗?
关于格式。您需要将第二列整体设置为格式:
(select format(sum(early_leave),2) from `attendance` where `attendance`.early_leave
> 0 and date(`attendance`.`date`) = date(att.date)) / 60
将其更改为
CAST((select format(sum(early_leave),2) from `attendance` where `attendance`.early_leave
> 0 and date(`attendance`.`date`) = date(att.date)) / 60 AS DECIMAL(12,2))
但是,这不能解决您的问题。如果某些结果正确无误,则问题很可能是计算或源数据。
另一方面,原始查询有点混乱。代替使用子查询,更好的解决方案是联接该表。这样的东西(未经测试,但证明了我的意思)。
SELECT
DATE(`att`.`date`) AS `dtDate`,
CAST(SUM(`att2`.`early_leave`) / 60 AS DECIMAL(12,2)) AS `EL`
FROM `attendance` AS `att`
INNER JOIN `attendance` AS `att2`
ON `att2`.`early_leave` > 0 AND DATE(`att2`.`date`) = DATE(`att`.`date`)
WHERE DATE(`att`.`date`) BETWEEN '2018-08-9' and '2018-08-23'
GROUP BY DATE(`att`.`date`)
ORDER BY DATE(`att`.`date`)