简体   繁体   English

查询根据创建日期时间的日期获取列的总和?

[英]Query to get sum of a column based on the date of it's created datetime?

I have a table with two columns, caloriesConsumed and createdAt with datatypes Int and DateTime respectively.我有一个包含两列的表, caloriesConsumedcreatedAt分别具有数据类型IntDateTime I want to get the sum of the numbers entered on the same date.我想得到在同一日期输入的数字的总和。

SELECT SUM(caloriesConsumed), createdAt
FROM record
GROUP BY createdAt;

As createdAt is of datatype DateTime , the columns are not grouped and returns all the records.由于createdAt的数据类型为DateTime ,因此未对列进行分组并返回所有记录。 How can I group by the date and ignore the time in the column?如何按日期分组并忽略列中的时间?

use a cast(createdAt as date) to convert the datetime to date使用cast(createdAt as date)将日期时间转换为日期

select sum(caloriesConsumed), cast(createdAt as date)
    from record
    group by cast(createdAt as date)
SELECT SUM(caloriesConsumed), createdAt  
FROM record  
GROUP BY DATE(createdAt);

here DATE() function only grabs the date and remove time from datetime这里DATE() function 只获取日期并从日期时间中删除时间

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM