ActiveRecord query that groups by ID and sums rows - ruby-on-rails

My Postgresql DB has this structure:
TABLE Orders
id (string)
userId (string)
prodId (string)
value (integer)
This is an example of data:
id userId prodId value
1 a#a.aaa prod1 5
2 b#b.bbb prod1 -1
3 a#a.aaa prod1 -4
4 a#a.aaa prod2 9
I want to do a query from ActiveRecord that sums all the values for a specific userId, so the query for (a#a.aaa) would return a LIST like this:
prod1 1
prod2 9
My first approach is this one, but it doesn't work:
orderList = Orders.select("SUM(orders.amount) AS num_prods").where((:userId => HERE_USER_ID).group(:prodId)
EDIT: rephrased thanks to feedback

Order.where(userId: id).group(:prodId).sum(:value) # replace `:id` with your value
This should give you a hash, like so
{1=>10, 2=>20, 5=>20}
the keys 1,2,5 represent the product id, and the values 10,20,20 represent the sum values.

Related

Return unique user doesn't work with group_by

I'm using the ajax datatable gem to display the client name and total points in a store. the store-clients table looks like this.
store_id
client_id
total_points
But as it will be a report, I don't want to show the same client twice, even to different stores. I am trying the following:
StoreClient.joins(:client).group(:client_id)
But I get this error: column "store_clients.id" must appear in the GROUP BY clause or be used in an aggregate function
If I add the store_clients id the result is not as expected.
The expected would be:
client_id | store_id | total_points
1 1 10
1 2 20
2 1 5
-----------------------------------
client_id | store_id | total_points
1 1 10
2 1 5
Assume initial result is an array store in instance variable #result you can get a unique result like this:
#result.uniq {|o| o.client_id }

Sort products by producer name otherwise by something else in a "Rails way"

My customer wants to order products by producer name if producer name is "ABC", otherwise order the result by parameters_count and images_count. My schema looks like this:
Parts
id int PK
producer_id int
images_count int
parameters_count int
Producers
id int PK
lauber_id String
name string
The result of the sorting should be that the products that have a producer of ABC should be on the list first, otherwise show the products that have images count and parameters count greater than 0.
What would be the best way of sorting the results in a "Rails way". So far I have this.
Part.joins('join producers on parts.producer_id = CAST(producers.lauber_id as INT)')
.order("CASE WHEN producers.name = 'ABC' then producers.name END, images_count, parameters_count desc")
Is there a better way?
You can't order some rows on different numbers of columns. You want to order on 3 things, the first of which is a boolean. And since "false" come before "true", you need to reverse the order:
producers.name = 'ABC' desc, images_count, parameters_count desc

Many-to-many SELECT divided into multiple rows for some reason

I have two tables joined via third in a many-to-many relationship. To simplify:
Table A
ID-A (int)
Name (varchar)
Score (numeric)
Table B
ID-B (int)
Name (varchar)
Table AB
ID-AB (int)
A (foreign key ID-A)
B (foreign key ID-B)
What I want is to display the B-Name and a sum of the "Score" values of all the As belonging to the given B. However, the following code:
WITH "Data" AS(
SELECT "B."."Name" As "BName", "A"."Name", "Score"
FROM "AB"
LEFT OUTER JOIN "A" ON "AB"."A" = "A"."ID-A"
LEFT OUTER JOIN "B" ON "AB"."B" = "B"."ID-B")
SELECT "BName", SUM("Score") AS "Total"
FROM "Data"
GROUP BY "Name", "Score"
ORDER BY "Total" DESC
The results display several rows for every "BName" with the "score" divided into semingly random increments between these rows. For example, if the desired result for Johnny is 12 and for April it's 25, the query may shows something like:
Johnny | 7
Johnny | 3
Johnny | 2
April | 19
April | 5
April | 1
etc.
Even after trying to nest the query and doing another SELECT with SUM("Score"), the results are the same. I'm not sure what I'm doing wrong?
Remove Score from the GROUP BY clause:
SELECT BName, SUM(Score) AS Total
FROM Data
GROUP BY BName
ORDER BY Total DESC;
The purpose of your query is to summarize by name, so name alone should appear in the GROUP BY clause. By also including the score, you will get a record in the output for each unique name/score combination.
Okay, I figured out my problem. Indeed, I had to GROUP BY "Name" only, but Firebird I thought wasn't letting me do that. Turns out it was just a typo. Oops.

Query column of arrays with array

I have a database column with the datatype array. How can I query an array with an array in rails? For example, I have an array of software for an OS in my Product table and I want to query them like this:
selected_products = ['Apple', 'Linux']
Software.where("'#{selected_products}' = ANY (osses)")
edit:
example of Software table:
id | software | osses |
_______________________________________________________
1 product 1 {'Windows', 'Apple', 'Android'}
2 product 2 {'Android', 'Linux'}
3 product 3 {'Windows,', 'Android'}
4 product 4 {'Windows'}
In which case I'd like the query to return id's 1 and 2 (since id 1 has a match in Apple and id 2 has a match in Linux.)
Please look into this gem.
And then do a query like
selected_products = ['Apple', 'Linux']
Software.where.overlap(osses: selected_products)

Core data fetch request with GROUP BY

I have a table in my application which consists of some names and phone numbers and orderIDs and dates (4 columns).
I want to get an array of all distinct phone numbers (Note that someone with a phone number may have several orderIDs).
Test case: suppose that this is the current records of my table.
Name phoneNumber orderID date
John 1234 101 2014-12-12
Susan 9876 102 2014-12-08
John 1234 103 2014-12-17
I want an array of distinct phone numbers only, something like: {1234, 9876}
How can I perform such a fetch in core data?
Any help would be much appreciated. Thank you.
P.S: As I knew in SQL I could do something like:
SELECT phoneNumber FROM orders
GROUP BY phoneNumber
You can use Distinct Keyword. so your query will become
SELECT DISTINCT phoneNumber FROM orders

Resources