mysql在case语句中使用date()

oipij1gg  于 2021-07-24  发布在  Java
关注(0)|答案(2)|浏览(410)

我正在尝试使用mysql中的date()函数,仅使用datetime格式中的日期来创建基于星期几的订单总数的案例。但是,当我运行此查询时,每个案例的值都为“0”。

select 
(CASE datetime WHEN date(datetime) = '2020-06-22' THEN count(order_id) ELSE 0 END) AS 'Mon'
,(CASE datetime WHEN date(datetime) = '2020-06-23' THEN count(order_id) ELSE 0 END) AS 'Tue'
,(CASE datetime WHEN date(datetime) = '2020-06-24' THEN count(order_id) ELSE 0 END) AS 'Wed'
,(CASE datetime WHEN date(datetime) = '2020-06-25' THEN count(order_id) ELSE 0 END) AS 'Thu'
,(CASE datetime WHEN date(datetime) = '2020-06-26' THEN count(order_id) ELSE 0 END) AS 'Fri'
from table;

当我运行下面的查询时,我确认了我确实获得了一个特定日期的所需输出。

select count(order_id) 
from table
where date(datetime) = '2020-06-22';
hgncfbus

hgncfbus1#

按以下方式发送查询:

select
sum( if( weekday(datetime) = 0,1,0)) as 'Mon',
sum( if( weekday(datetime) = 1,1,0)) as 'Tue',
sum( if( weekday(datetime) = 2,1,0)) as 'Wed',
sum( if( weekday(datetime) = 3,1,0)) as 'Thu',
sum( if( weekday(datetime) = 4,1,0)) as 'Fri',
sum( if( weekday(datetime) = 5,1,0)) as 'Sat',
sum( if( weekday(datetime) = 6,1,0)) as 'Sun'

;

你可以使用

WHERE datetime BETWEEN '2020-06-22' AND '2020-06-26'

如果你想得到一系列的日期

c9qzyr3d

c9qzyr3d2#

mysql有一个很好的特性,将布尔值视为数字,1表示真,0表示假。所以你可以把逻辑表达为:

select sum( weekday(datetime) = 0 ) as Mon,
       sum( weekday(datetime) = 1 ) as Tue,
       sum( weekday(datetime) = 2 ) as Wed,
       sum( weekday(datetime) = 3 ) as Thu,
       sum( weekday(datetime) = 4 ) as Fri,
       sum( weekday(datetime) = 5 ) as Sat,
       sum( weekday(datetime) = 6 ) as Sun

或:

select sum( date(datetime) = '2020-06-22' ) as Mon,
       sum( date(datetime) = '2020-06-23' ) as Tue,
       sum( date(datetime) = '2020-06-24' ) as Wed,
       sum( date(datetime) = '2020-06-25' ) as Thu,
       sum( date(datetime) = '2020-06-26' ) as Fri,
       sum( date(datetime) = '2020-06-27' ) as Sat,
       sum( date(datetime) = '2020-06-28' ) as Sun

您的查询无法工作,因为它是聚合查询( COUNT() )但是你的文章中有未汇总的专栏 SELECT . mysql应该会返回一个解析错误——最新版本会返回。
我还强烈建议您不要使用单引号来分隔列。原因有三:
你的列名很好,不需要转义。
单引号只能用于字符串和日期常量。
如果确实需要转义标识符,可以使用反记号。

相关问题