Date column arithmetic in PostgreSQL query

陌路散爱 提交于 2019-12-02 14:15:06

问题


I have two tables that look like this:

CREATE TABLE table1 (user_id int, the_date date);
CREATE TABLE table2 (user_id int, the_date date, something_else real);

I am writing a query that looks like this

CREATE TABLE foo AS 
 SELECT t1.user_id
 , (t1.the_date - (t2.the_date - t1.the_date)::int) start_date
 FROM table1 t1, table2 t2 
 where t1.user_id=t2.user_id
 ;

When I run the above query, I get the following error displayed on the psql console:

ERROR:  syntax error at or near "$1"
LINE 1: ...the_date - (t2.the_date - t1.the_date)::int)  $1 ...

                                                             ^

The second column in the query result is to show a date which is N days BEFORE the date in table1, where N is the difference (in days) between the date in table2 and table1.

Note: table2 will always have has later dates than the dates in table1.

How can I perform this date calculation and store the result as a new column alias in my query?

I am using PG 8.4.


回答1:


As @LisMorski commented, you would need to table-qualify t1.user_id to disambiguate the way you have it.

I would also suggest a couple of other adjustments:

CREATE TABLE foo AS 
 SELECT user_id
       ,(t1.the_date - (t2.the_date - t1.the_date)) AS start_date
 FROM table1 t1
 JOIN table2 t2 USING (user_id);
  • Subtracting two dates yields integer. Cast was redundant.

  • For column aliases it's best to use the AS keyword (while it's generally OK to omit it for table aliases). I quote the manual here:

You can omit AS, but only if the desired output name does not match any PostgreSQL keyword (see Appendix C). For protection against possible future keyword additions, it is recommended that you always either write AS or double-quote the output name.)

  • If you join your tables with an explicit JOIN clause us9ing the USING keyword, then there is only one column user_id in the result set and you don't have to table-qualify it any more.


来源:https://stackoverflow.com/questions/11536385/date-column-arithmetic-in-postgresql-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!