I
I
Ilnar252018-02-28 15:22:07
SQL
Ilnar25, 2018-02-28 15:22:07

How to get the sum of certain fields from the database?

I have this table

create_table "orders", force: :cascade do |t|
  t.bigint "user_id"
  t.bigint "store_id"
  t.string "recipient_adress"
  t.string "sender_coordinates", default: [], array: true
  t.string "recipient_coordinates", default: [], array: true
  t.datetime "created_at"
  t.boolean "rendition", default: false
  t.float "shipping"
  t.float "total_price"
  t.index ["store_id"], name: "index_orders_on_store_id"
  t.index ["user_id"], name: "index_orders_on_user_id"
end

How to get information on revenue for each day?
In detail: how to get the sum of cost values ​​(:total_price) sorted by each day (:created_at) in one query. For search, we have a value for the field (: store_id). Something like this [{created_at: value, sum: value}, {......}]. Preferably in pure SQL. Can you help?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Ruslan., 2018-02-28
@Ilnar25

select created_at, sum(total_price)
from orders
where store_id = ?
group by created_at
order by created_at desc
Only there is a nuance, if the created_at field has a date with time, then for grouping you need to clear the date from the time.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question