需要从SQL中的时间戳显示星期几

时间:2018-01-23 14:50:49

标签: mysql sql

我希望从表格中的created列(数据类型为时间戳)中提取星期几,并在整个数据集中按天计算结果。实施例

surveys

2016-03-21 20:21:30
2016-03-21 20:23:23
2016-03-21 20:24:07
2016-03-22 14:21:20
2016-03-25 12:05:41
2016-03-29 11:33:02
2016-03-29 23:44:03
2016-04-04 15:10:27 

预期输出为:

Monday - 4
Tuesday - 3
Friday - 1

2 个答案:

答案 0 :(得分:2)

刚刚在sqlfiddle上测试了这个。您可以忽略这些创建和插入命令,因为您已有数据。

create table yourTable (created timestamp);
insert into yourTable values ('2016-03-21 20:21:30');
insert into yourTable values ('2016-03-21 20:23:23');
insert into yourTable values ('2016-03-21 20:24:07');
insert into yourTable values ('2016-03-22 14:21:20');
insert into yourTable values ('2016-03-25 12:05:41');
insert into yourTable values ('2016-03-29 11:33:02');
insert into yourTable values ('2016-03-29 23:44:03');
insert into yourTable values ('2016-04-04 15:10:27');

SELECT   count(created), --get the count of days
         dayname(created) AS day --function to get the day of the week via the date
FROM     yourTable
GROUP BY day --seperates the data according the the day of the week 

这将返回您的预期结果集。

count(created)    day
  1               Friday  
  4               Monday  
  3               Tuesday 

答案 1 :(得分:1)

您只需要计算日期字段https://dev.mysql.com/doc/refman/5.7/en/counting-rows.html

的值

然后使用DAYNAME()函数https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html

显示它

EG。 “TABLE”是表名,DATE_HOUR是日期

的字段名称
SELECT DAYNAME(DATE_HOUR), count(DATE_HOUR)
FROM `TABLE`
GROUP BY DATE_HOUR