I have a trading model which has got 2 fields, number_of_share and price_per_share.
I want to showcase it in a pie chart and to do that I have to find all the trading objects associated with a user and then add all the trading objects which have same price_per_share and add their number_of_shared as well.
Example :-
trading id: 1, price_per_share: 10, number_of_shares: 20
trading id: 2, price_per_share: 10, number_of_shares: 12
trading id: 3, price_per_share: 12, number_of_shares: 10
now i want to add all the price_per_share which have got similar values (10 in this case). How can I do that ?
This should work:
Trading.group(:price_per_share).sum(:number_of_shares)
# => {10=>32, 12=>10}
The SQL will be something like:
SELECT SUM(`tradings`.`number_of_shares`) AS sum_number_of_shares, price_per_share AS price_per_share FROM `tradings` GROUP BY `tradings`.`price_per_share`
Hope I understand that right, but:
Trading.where(:price_per_share => 10).sum(:number_of_shares)
should give you the result you are looking for.
Related
I am new to Rails, and I am given a code, but I do not understand what it means (I am actually just trying to understand the Rails code because I am tasked to use the same logic inside another program)
here is the code
ids = [1, 2, 3]
users = User.where(account_id: ids)
output = Worksheet.where(created_by: users).as_json(only: [:created_at, :id]).group_by_week(week_start: :monday)
{|w| w["created_at"]}
i am not sure if I am following along, but from what i understand, it seems like i am querying the users with id 1, 2, 3, and finding the worksheets that are created by said users, and grouping them by week. However, I do not really understand what the 'only: [:created_at, :id]' does, but I checked through the columns, and there were columns 'created_at' and 'id' inside the worksheet table. Also, I am totally lost about what the below code is about
{|w| w["created_at"]}
and finally, is it possible to let me know what the output of the program would be like? thanks all!
The as_json(only: [:created_at, :id]) part says "convert this result to json but I only want those two columns." Documentation.
The group_by_week(week_start: :monday) takes a block, which is what the { |w| w["created_at"] } part is. It will go through each result from all the previous operations, assign each in turn to w, and then use w["created_at"] for the group_by_week function (for comparison purposes, most likely).
I would like to see/view all my contacts based on the same company name, whenever I filter my worksheet.
For example, My table:
If I choose to filter Contact Name: "Adi" I would like to see this:
Because Adi and Dan belong to the same Company. another example could be, If I choose to filter
Last Modified field: " 3/05/2020", The result should be:
Again because Adi and Dan belong to the same Company. The solution could be on app script as well.
try:
=FILTER(A:C, REGEXMATCH(A:A, VLOOKUP(G1, {B:B, A:A}, 2, 0)))
=A2=VLOOKUP(G$1, {B:B, A:A}, 2, 0)
I have a table of Album's that has a date column named release_date.
I want to get a list of all the decades along with the number of albums released in that decade.
So, the output might be something like:
2010 - 11
2000 - 4
1990 - 19
1940 - 2
Ruby 2.3.1 w/ Rails 5 on Postgres 9.6, FWIW.
This is essentially a followup question to a previous one I had: Group by month+year with counts
Which may help with the solution...I'm just not sure how to do the grouping by decade.
Using Ruby for processing db data is inefficient in all senses.
I would suggest doing it on the database level:
Album.group("(DATE_PART('year', release_date)::int / 10) * 10").count
What happens here, is basically you take a year part of the release_date, cast it to integer, take it's decade and count albums for this group.
Say, we have a release_date of "2016-11-13T08:30:03+02:00":
2016 / 10 * 10
#=> 2010
Yes, this is pretty similar to your earlier question. In this case, instead of creating month/year combinations and using the combinations as your grouping criteria, you need a method that returns the decade base year from the album year.
Since you have a pattern developing, think about writing the code so it can be reused.
def album_decades
Album.all.map { |album| album.release_date.year / 10 * 10 }
end
def count_each(array)
array.each_with_object(Hash.new(0)) { |element, counts| counts[element] += 1 }
end
Now you can call count_each(album_decades) for the result you want. See if you can write a method album_months_and_years that will produce the result you want from your earlier question by calling count_each(album_months_and_years).
There are more than one possible solution to your problem, but I would try:
Add a new column to the Album table, called decade. You can use a migration for this porpoise.
Create a callback (its like a trigger, but in the programmer side) that set the decade value before saving the Album in the DB.
Finally you can use this useful query to group the Albums by decade. In your case would be Album.group(:decade).count wich would give you a hash with the numbers of Albums by decade.
...
Profit ?
Jokes aside, the callback should be something like:
class Album < ActiveRecord::Base
# some code ...
before_save :set_decade # this is the 'callback'
# ...
private
def set_decade
self.decade = self.release_date.year / 10
end
Then, if you use the step 3, it would return something like:
# => { '195' => 7, '200' => 12 }
I did not test the answer, so try it out and tell me how it went.
I have a model with following columns
Charges Model
Date
fee
discount
Data
1/1/15, 1, 1
1/1/15, 2, 1
2/2/15, 3, 3
I have a few named scopes like this_year
I want to do something like Charges.this_year.summed_up
How do I make a named scope for this.
The returned response then should be:
1/1/15, 3, 2
2/2/15, 3, 3
Assuming you have a model with a date field(eg. published_at) and 2 integer fields(eg. fee, discount). You can use "group" method to run GROUP BY on published_at. Then just use sum method if you want only sum of one fields. If you want more than one field, you have to run a select with SQL SUMs inside, to get multiple column sums. Here is an example.
Charge..group(published_at)
.select("published_at, SUM(fee) AS sum_fee, SUM(discount) AS sum_discount")
.order("published_at")
Note: Summarized fields won't show up in rails console return value prompt. But they are there for you to use.
Depending upon what end result you want, you may want to look at .group(:attribute) rather than .group_by:
Charge.group(:date).each do |charge|
charge.where('date = ?', charge.date).sum(:fee)
charge.where('date = ?', charge.date).sum(:discount)
end
I found this approach easier, especially if setting multiple conditions on the data you want to extract from the table.
In any case, I had an accounting model that presented this kind of issue where I needed credit and debit plus type of payment info on a single table and spent a fruitful few hours learning all about group_by before realizing that .group() offered a simple solution.
I have a dashboard I'm working on that basically lists all the users of the system and the number of activities they have in each month. I'm curious on what others think would be an efficient way to compile this data. I'm thinking I should eventually attempt to get it in this format:
{
user1 => { :jan => 13, :feb => 21, :mar => 4, ... },
user2 => { :jan => 16, :feb => 18.... },
....
}
Though I'm by no means married to that idea. Here is screenshot of what I'm working towards to help give you a better idea:
http://i.stack.imgur.com/HbSln.png
If you're using an activity log to track activity (one record per activity), then it should be pretty simple. Basically, COUNT(*) your activity records per user, and GROUP them by the month in which they occurred.
Alternatively, and depending on your requirements, you could also just have a single record per user, per month (instead of a log), with an incrementing count of the number of activities.