【问题标题】:how can format column name in case when in sql [closed]在sql中如何格式化列名[关闭]
【发布时间】:2022-01-16 19:25:29
【问题描述】:

我有created_at 列(日期类型)我需要在大小写之前只使用year and month 对其进行格式化。我尝试了这个查询,但它给出了0,而且我的表中有用户!

我正在使用 MySQL:

select 
  count(case when DATE_FORMAT(created_at, '%Y-%c') = 2022-1 then 1 end)
  as one from `users` limit 1

【问题讨论】:

  • 2022-1 是等于 2021 的算术表达式。引号在哪里?
  • @Akina 我是多么愚蠢! :(
  • 使用SELECT COUNT(1) AS one FROM users WHERE created_at BETWEEN '2022-01-01' AND '2022-01-31 23:59:59'。如果created_at 的索引存在,则查询可以使用它。

标签: mysql sql


【解决方案1】:

你必须使用字符串而不是算术表达式:

select 
  count(case when DATE_FORMAT(created_at, '%Y-%c') = '2022-1' then 1 end)
  as one from `users` limit 1

你的表情是一样的

select 
  count(case when DATE_FORMAT(created_at, '%Y-%c') = 2021 then 1 end)
  as one from `users` limit 1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-08
    • 1970-01-01
    • 2013-01-29
    • 1970-01-01
    相关资源
    最近更新 更多