gpt4 book ai didi

sql - rails/SQL : Group by and sum each day in the last 2 weeks

转载 作者:太空宇宙 更新时间:2023-11-03 18:23:56 24 4
gpt4 key购买 nike

我正在尝试总结过去两周的每一天。

这段代码:

Invoice.group('date(filled_at)').sum(:lines_price).to_a

返回:

[["2012-12-15", #<BigDecimal:ac40068,'0.19275E4',18(45)>], ["2012-12-17", #<BigDecimal:a759234,'0.764235E3',18(45)>]]

这是正确的,但我需要它返回过去两周的值,即使该值是 0.0

所以结果应该是:

[["2012-12-03", 0.0], ... , ["2012-12-17", #<BigDecimal:a759234,'0.764235E3',18(45)>]]

谢谢。

更新

having("date(filled_at) > ?", Date.today - 14)

解决了过去 14 天的问题。但我仍然不知道如何显示 0.0 值。

最佳答案

您将很难在 SQL 中执行此操作,因为您试图强制数据库返回不存在的值。在 ruby​​ 中执行此操作要容易得多。这是一个简洁的方法:

summary = Invoice.group('date(filled_at)').sum(:lines_price).to_a
past_two_weeks = ((Date.today - 14).. Date.today)

final_result =Hash[*past_two_weeks.map(&:to_s).product([0.0]).flatten].merge Hash[*summary.flatten]

final_result.to_a

关于sql - rails/SQL : Group by and sum each day in the last 2 weeks,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13924122/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com