选择distinct与多列rails mysql

时间:2017-09-17 23:11:22

标签: ruby-on-rails ruby

现在,我有mysql数据库和这段代码:

Report.select('date, title, info').distinct

它等同于这个SQL查询:

SELECT DISTINCT
    date,
    title,
    marketplace
FROM
    reports

但是,如果我不仅要选择date, title and info,还要选择price之类的更多参数,该怎么办?但我希望结果仅基于date,title and info来区分 我该怎么办? 我想到了挖掘某个地方的方法。

1 个答案:

答案 0 :(得分:0)

可以通过指定SQL查询应按哪些列进行分组来实现此目的。

作为一个例子,我将展示想要总结价格的情景,因为你没有包括你想要如何使用价格(如Danil Speransky所说)。

计算每个日期,标题和信息的所有价格总和:

@reports = Report.select([:date, :title, :info]).group([:date, :title, :info]).sum(:price)
(4.1ms)  SELECT SUM(`reports`.`price`) AS sum_price, date AS date, title AS title, info AS info FROM `reports` GROUP BY date, title, info
=> {["[date]", "[title]", "[info]"]=>1234,
    ["[date]", "[title2]", "[info]"]=>5678,
    ...
}

然后你可以循环访问并像这样访问

@reports.each_pair do |columns, sum_price|
  [0] # date
  [1] # title
  [2] # info
  sum_price # The sum of all prices
end

另一种选择是像这样手动构建选择查询

@reports = Report.select("SUM(`reports`.`price`) AS sum_price, date AS date, title AS title, info AS info").group([:date, :title, :info])
# Results in same SQL query, but will instantiate a model record for each row
=> [#<Report date: "2017-09-18", title: "[Title]", info: "[Info]">,
    #<Report date: "2017-09-18", title: "[Title2]", info: "[Info]">,
    ...
]

即使被检查的记录不会显示:sum_price列,仍然可以像这样访问

@reports.each do |report|
  report.date
  report.title
  report.info
  report.sum_price
end