我有一个 PostgreSQL 查询,它按月汇总值,从日期中提取月份值:
SELECT vendors.name AS vendor,
SUM(purchases.invoice_total) AS invoice_total,
EXTRACT(MONTH FROM purchases.date) AS date
FROM vendors, purchases
WHERE purchases.vendor_id = vendors.id
AND purchases.store_id = ?
AND purchases.purchase_department_id = ?
AND (purchases.date BETWEEN ? AND ?)
GROUP BY vendor, EXTRACT(MONTH FROM purchases.date)
ORDER BY vendor, date;
直接在 DB 控制台中执行查询后,我得到如下信息:
+------------------------------------+---------------+------+
| vendor | invoice_total | date |
+------------------------------------+---------------+------+
| Store 1 | 448.56 | 1 |
| Store 1 | 263.44 | 2 |
| Store 1 | 939.47 | 3 |
使用 Rails 的find_by_sql
功能时会出现问题。和值正确返回,但日期值返回为零vendor
。invoice_total
#<Purchase date: nil, invoice_total: #<BigDecimal:85c75c8,'0.26344E3',18(18)>>
这是我的电话。我什至尝试过硬编码值,但什么都没有,但就像 Extract 函数不会在 Rails 中执行:
<% @purchasesSQL = Purchase.find_by_sql(["SELECT vendors.name AS vendor, SUM(purchases.invoice_total) AS invoice_total,
EXTRACT(MONTH FROM purchases.date) AS date
FROM vendors, purchases
WHERE purchases.vendor_id = vendors.id
AND purchases.store_id = ?
AND purchases.purchase_department_id = ?
AND (purchases.date BETWEEN ? AND ?)
GROUP BY vendor, EXTRACT(MONTH FROM purchases.date)
ORDER BY vendor, date;", @store.id, purchase_department.id, @start, @end])
%>
我已经进行了一些调试,并且我传递的值不是零也不是错误的。