【问题标题】:How to alias a Date in a mySql group clause, using Ruby on Rails?如何使用 Ruby on Rails 为 mySql 组子句中的日期起别名?
【发布时间】:2021-08-03 05:05:57
【问题描述】:

我正在尝试检索开始日期和结束日期之间的设备读数。然后从结果中返回一个包含日期、计数总和和 m 值的数组。但是,当我尝试在我的 group 子句中为转换后的日期时间设置别名时,我不断收到语法错误。由于我需要将日期时间存储为日期对象,我如何在我的 group 子句中正确地为它起别名,这样我就可以采摘它了?

错误:

Mysql2::Error: 你的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 1 行的“作为日期”附近使用正确的语法:SELECT date, sum(counts) as counts, ANY_VAUE(m) as m FROM device_readings WHERE device_readings。 device_id = 1 AND (device_readings.datetime`在“2021-04-01 00:00:00”和“2021-05-01 00:00:00”之间)按日期分组(CONVERT_TZ(日期时间,“格林威治标准时间”,“ America/New_York')) 作为日期)

记录列

datetime:时间对象,counts:number,m:number

查询:

    readings = @device.readings.
    where(:datetime => @start_date..@end_date).
    group("DATE(CONVERT_TZ(datetime, 'GMT', 'America/New_York')) as date").
    order("datetime ASC").
    pluck("date, sum(counts) as counts, ANY_VALUE(m) as m")

【问题讨论】:

    标签: mysql ruby-on-rails ruby activerecord


    【解决方案1】:

    您不能在 SQL 的 GROUP BY 子句中为列设置别名。即使您可以这样做也毫无意义,因为您实际上并没有选择该列,并且您也不能在查询中的其他任何地方重用它。

    readings = @device.readings.
      where(datetime: @start_date..@end_date).
    
      group(:date).
      order(datetime: :asc).
      pluck(
        "DATE(CONVERT_TZ(datetime, 'GMT', 'America/New_York')) as date",
        "sum(counts)",
        "ANY_VALUE(m)"
      )
    

    请注意,如果您使用 .pluck 别名,则列是没有意义的,除非您在查询中引用它们。 pluck 的结果始终是一个数组数组。如果你想要哈希,你想压缩结果:

    readings.map {|r| Hash[[:date, :counts, :m].zip(r)] }
    

    你也可以创建a SQL view 和一个相应的模型,如果你想看的话。

    【讨论】:

      【解决方案2】:

      您不能将 Group by 定义为列并将其用于您的选择,反之亦然

      readings = @device.readings.
      where(:datetime => @start_date..@end_date).
      group("DATE(CONVERT_TZ(datetime, 'GMT', 'America/New_York'))").
      order("datetime ASC").
      pluck("DATE(CONVERT_TZ(datetime, 'GMT', 'America/New_York')) as date1 , sum(counts) as counts, ANY_VALUE(m) as m")
      

      【讨论】:

      • 您可以在大多数 RDBMS:s 上重复使用您在 where、group、order 和 having 子句中选择的列。我相信甲骨文是个例外。
      • mysql 使用有子句而不是 where 子句,group by 也需要来自 from 子句,我很惊讶 constrict 仍然有效,相当扭曲
      猜你喜欢
      • 2011-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-06
      • 1970-01-01
      • 2016-05-15
      相关资源
      最近更新 更多