【发布时间】:2015-01-31 03:59:41
【问题描述】:
我的表格中有一个日期列,我想在某个年月之后“过滤”/选择项目。因此,如果我有 2010 年以后的数据,我有一个用户输入,将“2011-10”指定为他们想要查看数据的“最早日期”。
我当前的 SQL 如下所示:
select round(sum(amount), 2) as amount,
date_part('month', date) as month
from receipts join items
on receipts.item = items.item
where items.expense = ?
and date_part('year', date)>=2014
and funding = 'General'
group by items.expense, month, items.order
order by items.order desc;
在“where”的第二部分,我不想执行 year >= 2014,而是将to_char(date, 'YY-MMMM') >= ? 作为另一个参数,然后传入“2011-10”。但是,当我这样做时:
costsSql = "select round(sum(amount), 2) as amount,
to_char(date, 'YY-MMMM') as year_month
from receipts join items
on receipts.item = items.item
where items.expense = ?
and year_month >= ?
and funding = 'General'
group by items.expense, year_month, items.order
order by items.order desc"
并用我的两个参数调用它,我得到一个 postgres 错误:PG::UndefinedColumn: ERROR: column "year_month" does not exist。
编辑:我将我的 YYYY-MM 字符串转换为日期并将其作为我的参数传入,它正在工作。但我仍然不明白为什么在 select 子句中创建该列后出现“列不存在”错误 - 有人可以解释一下吗?这样创建的列不能用在where子句中吗?
【问题讨论】:
-
为什么不使用
date >= ?::date并传入2011-10-01?
标签: ruby postgresql