【问题标题】:ER_OPERAND_COLUMNS: Operand should contain 1 column(s)ER_OPERAND_COLUMNS:操作数应包含 1 列
【发布时间】:2020-11-01 16:09:55
【问题描述】:

所以我试图运行一个简单的查询来计算每个用户在过去 12 个月内的事件。 我已将日期作为字符串 (varchar) 导入,因为如果我使用 datetime 它只会将空值添加到该列中(即 0000-00-00)

CREATE table `DB`.`EVENTS`(user_id varchar(30)not null, datetime varchar(50) not null);
insert into `DB`.`EVENTS` VALUES ('1', 'Jun 14, 2020 3:35 PM'),
    ('2', 'Jun 3, 2020 3:35 PM'),
    ('2', 'May 17, 2020 1:00 PM'),
    ('3', 'Jan 5, 2020 2:00 PM'),
    ('4', 'Jun 3, 2020 12:00 PM'),
    ('5', 'Jun 24, 2020 5:00 PM'),
    ('3', 'Jan 15, 2019 2:00 PM');

所以我需要将 str 转换为日期并使用嵌套查询(此查询独立工作):

select user_id, count(*) from DB.EVENTS where user_id in (select user_id, str_to_date(datetime, '%M %d,%Y') as date
    from DB.EVENTS
    having date >= DATE_ADD(current_timestamp(), interval -12 month));

但我收到错误 ER_OPERAND_COLUMNS:操作数应包含 1 列。 如果我尝试删除列 user_id 我再次得到空值...... 谁能指导我?

【问题讨论】:

  • 您的子查询返回两列,从选择列表中删除 str_to_date(datetime, '%M %d,%Y') 计算并将其移至 HAVING(或更好的 WHERE)
  • 如果我将其从选择部分中删除,则会出现错误:ER_BAD_FIELD_ERROR: Unknown column 'datetime' in 'have Clause'
  • 你到底想要什么?目前,如果用户在去年有 any 事件,则您计算他的 所有 事件。这可以在没有子查询的情况下轻松完成。
  • 我想统计每个用户在过去 12 个月内发生的所有事件。我不希望输出中的日期,但我需要日期转换/间隔在查询中。
  • 您无需在选择列表中添加列即可在 WHERE/HAVING 中使用它。

标签: sql datetime


【解决方案1】:

如果您只想统计去年的事件,请在 WHERE 中进行过滤:

select user_id, count(*) 
from DB.EVENTS
where str_to_date(datetime, '%M %d,%Y') -- only rows from the last  
    >= DATE_ADD(current_timestamp(), interval -12 month)
group by user_id
;

如果您想统计 所有 事件,如果用户在去年有 任何 事件,您可以应用 HAVING 中的逻辑:

select user_id, count(*) 
from DB.EVENTS
group by user_id
having max(str_to_date(datetime, '%M %d,%Y')) -- any event in the last year 
    >= DATE_ADD(current_timestamp(), interval -12 month)
;

【讨论】:

    猜你喜欢
    • 2014-11-07
    • 1970-01-01
    • 2023-03-29
    • 2012-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多