简体   繁体   English

在 sql 中按日期分组并以日期时间显示

[英]Group by date and show in date time in sql

i want to count the data then group by date (and it show in date time).我想计算数据然后按日期分组(并以日期时间显示)。 the result of data type must date time not var char.数据类型的结果必须是日期时间而不是 var char。 any idea?任何想法?

table_a表_a

timestamp
2020-11-28 04:00:00
2020-11-28 05:00:00
2020-11-29 01:00:00
2020-11-29 02:00:00
2020-11-29 03:00:00

expected result:预期结果:

timestamp                 count
2020-11-28 00:00:00       2
2020-11-29 00:00:00       3

if i query this:如果我查询这个:

select date(timestamp), count(*) as count
from table_a
group by date(timestamp)

the result is:结果是:

timestamp     count
2020-11-28     2
2020-11-29     3

You can truncate the time part with DATE(timestamp) and cast back to DATETIME with the function CAST() :您可以使用DATE(timestamp)截断时间部分并使用 function CAST()转换回DATETIME

SELECT CAST(DATE(timestamp) AS DATETIME) AS my_datetime, 
       COUNT(*) AS count 
FROM table_a
GROUP BY my_datetime;

See the demo .请参阅演示
Results:结果:

> my_datetime         | count
> :------------------ | ----:
> 2020-11-28 00:00:00 |     2
> 2020-11-29 00:00:00 |     3

Use this code:使用此代码:

CAST(MED_TO_DT AS DATETIME)

You can use CAST date field to datetime.您可以将CAST日期字段用于日期时间。

If you want to group by the date AND time, use this query:如果要按日期和时间分组,请使用以下查询:

select CONVERT(timestamp, datetime) as timestamp, count(1) as count
from table_a
group by CONVERT(timestamp, datetime)

Otherwise, if you truly want to group by the date ONLY and then display the timestamp as 00:00:00, then use this query:否则,如果您真的只想按日期分组,然后将时间戳显示为 00:00:00,请使用以下查询:

select CONVERT(CONVERT(timestamp, date), datetime) as timestamp, count(1) as count
from table_a
group by CONVERT(timestamp, date)

MYSQL: MYSQL:

SELECT Concat(Cast(timestamp AS DATE), " 00:00:00") AS timestamps, 
       Count(*)                                     AS count 
FROM   table_a 
GROUP  BY timestamps 

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

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