简体   繁体   中英

Calculating difference between two dates in rails activerecord select statement

I have a Placements model, which contains check_in and check_out date columns, as well as an integer field 'places'. I'm trying to write a query (postgres) which calculates the total 'person-nights' for a user. A User has many Placements through Listings, so for each placement, I need to find the difference between the check_out and check_in dates in days, and multiply this by the number of places in that placement. Ideally I can do this in one query, something along the lines of the following logic:

  hosted_personnights_count = current_user.hosted_placements
    .select("SUM((placements.check_out - placements.check_in)*placements.people) as datediff")
    .where("placements.confirmed_at IS NOT NULL and placements.check_out < ?", Date.today)
    .group(:user_id)

Obviously this isn't the right syntax, but I thought it was easier to explain this way than try to list all the postgres functions I've tried that don't work. Any ideas? Placements table looks something like:

    create_table "placements", force: true do |t|
     t.integer  "user_id"
     t.integer  "listing_id"
     t.date     "check_in"
     t.date     "check_out"
     t.integer  "people"
     t.datetime "confirmed_at"
     t.datetime "created_at",         null: false
     t.datetime "updated_at",         null: false
    end

Your query is simple as

SELECT SUM((check_out - check_in) * people) AS all
  FROM placements
 WHERE confirmed_at IS NOT NULL
   AND check_out < ?
   AND user_id = ?

You don't need a GROUP BY clause, if you want to sum it all up.

And make sure you don't accidentally select another column (after all ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM