Date column arithmetic in PostgreSQL query

后端 未结 1 413
夕颜
夕颜 2020-12-22 06:49

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         


        
相关标签:
1条回答
  • 2020-12-22 07:21

    You would need to table-qualify t1.user_id to disambiguate. Plus 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.

    • Don't omit the AS keyword for column aliases - while it's generally OK to omit AS for table aliases. The manual:

      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.)

    • Joining tables with a USING clause only keeps one instance of the joining columns(s) (user_id in this case) in the result set and you don't have to table-qualify it any more.

    0 讨论(0)
提交回复
热议问题