Rails - group by results of an aggregate function? - sql

Let's say I have a table of Purchases that contain a Customer customer_id and the money they spent on the purchase price. I want to sum the total spent by each customer and then find the frequency of those sums.
I tried something like:
Purchase.
group(:customer_id).
select("SUM(price)").
group("SUM(price)").
count
but received the error ActiveRecord::StatementInvalid: PG::GroupingError: ERROR: aggregate function calls cannot be nested
There's a two step process in which I pluck "SUM(price)" as an array and convert it to a hash with the summed price as the key and the frequency as the value, but I was wondering if there was a one-step query using the Rails syntax.

Do you have other columns on that table ?
Try to group them as well.
Purchase.select("SUM(price),purchase_id").group_by(:purchase_id)
Make sure you take only columns you need and group them.

Related

How to get the Average of a Row After Getting Count?

I am trying to use an aggregate function to get the average(count( of a row in SQL Server. However, I continue to get this message:
"Cannot perform an aggregate function on an expression containing an aggregate or a subquery."
In the first picture is the table, in the second picture is the table with the counts for each officer_id, I am trying to find the average amount of calls per officer and cannot seem to find the right SQL query to do it.
The query I thought may work is:
SELECT AVG(COUNT(officer_id))
FROM crime_officers
ORDER BY officer_id;
But this is where I get the aggregate error. Does anyone have any recommendations?
UPDATED table with this query
SELECT officer_id, COUNT(crime_id)
FROM crime_officers
GROUP BY officer_id;
Original table: crime_officers
If I understand correctly, this query provides the average number of crimes per officer. A single value, which is equal to the total number of crimes divided between all officers.
SELECT COUNT(*)*1.0/COUNT(distinct officer_id) as 'Average Crimes per Officer'
FROM crime_officers;

Google Sheets Query Function. How can I get only Unique or Distinct Rows?

I am trying to answer a question on a case using the Query function on Google Sheets and am stuck on a particular problem.
I need to get the total number of unique orders per year. I used the formula below and managed to get the total orders per year.
=QUERY(raw_data!$A$1:$U$9995, "select YEAR(C), COUNT(B) group by YEAR(C)", 1)
Where column C is the date and B is the order_id.
The problem is that this returns a total of 9994 orders and includes duplicates of the same order. For example, if a customer purchased 3 different products, they would each be given a line in the database and would count as 3 of the 9994 orders. However, they all have the same order_id.
I need to get the number of unique orders per year. I know this number is 5009 since I did some manual research through Excel, but wanted to find that same total, separated by year, using the Query Function since this is a case to test my SQL Knowledge.
Is this possible? Does the Query Function have a way to get the count for unique order_ids? Thank you very much for your help!
See if this helps
=QUERY(UNIQUE(raw_data!$B$1:$C$9995), "select YEAR(Col2), COUNT(Col1) where Col2 is not null group by YEAR(Col2)", 1)

How to display the sum of amount with between two given dates with groupwise, in Laravel?

I want to display the customer name and its sum of all the bills he paid between specific dates. I also want the whole list of customers between the 2 given dates with sum of their total bills.
In list what I want is first Customer Name then its regarding sum of all the bill totals.
I have tried many options for it one where I am getting the sum of that bill only every bill is appearing separately while I want to group it by the customer thats all.
Raw query is working in phpMyAdmin but I failed to convert it to Laravel Eloquent. I want to make this raw query to work using Eloquent.
Query:
select customer_id,sum(total),sum(totalcgst),sum(totalsgst),
sum(totaligst) from sales where
date BETWEEN '2018-03-01' and '2018-03-31'
group by customer_id
This is the result I am getting in database
Try this:
ORM_NAME::selectRaw('customer_id, sum(total), sum(totalcgst), sum(totalsgst)')->whereBetween('date', ['2018-03-01', '2018-03-01'])->groupBy('customer_id)->get();

Select and manipulate SQL data, DISTINCT and SUM?

Im trying to make a small report for myself to see how my much time I get inputed in my system every day.
The goal is to have my SQL to sum up the name, Total time worked and Total NG product found for one specific day.
In this order:
1.) Sort out my data for a specific 'date'. I.E 2016-06-03
2.) Present a DISTINCT value for 'operators'
3.) SUM() all time registered at this 'date' and by this 'operator' under 'total_working_time_h'
4.) SUM() all no_of_defects registered at this 'date' and by this 'operator' under 'no_of_defects'
date, operator, total_working_time_h, no_of_defects
Currently I get the data I want by using the Query below. But now I need both the DISTINCT value of the operator and the SUM of the information. Can I use sub-queries for this or should it be done by a loop? Any other hints where I can learn more about how to solve this?
If i run the DISTINCT function I don't get the opportunity to sum my data the way I try.
SELECT date, operator, total_working_time_h, no_of_defects FROM {$table_work_hours} WHERE date = '2016-06-03' "
Without knowing the table structure or contents, the following query is only a good guess. The bits to notice and work with are sum() and GROUP BY. Actually syntax will vary a bit depending on what RDBMS you are using.
SELECT
date
,operator
,SUM(total_working_time_h) AS total_working_time_h
,SUM(no_of_defects) AS no_of_defects
FROM {$table_work_hours}
WHERE date = '2016-06-03'
GROUP BY
date
,operator
(Take out the WHERE clause or replace it with a range of dates to get results per operator per date.)
I'm not sure why you are trying to do DISTINCT. You want to know the data, no of hours, etc for a specific date.
do this....
Select Date, Operator, 'SumWorkHrs'=sum(total_working_time_h),
'SumDefects'=sum(no_ofDefects) from {$table_work_hours}
Where date='2016-06-03'
Try this:
SELECT SUM(total_working_time) as total_working_time,
SUM(no_of_defects) as no_of_defects ,
DISTINCT(operator) AS operator FROM {$table_work_hours} WHERE
date = '2016-06-03'

Getting average low and high bids in SQL

I am pretty new to SQL and am working with a (what I expected to be easy) little bidding tool.
I am trying to compute average lows and highs from the same column. I have managed to figure out how to use SQL's MIN, MAX, AVG functions, but how would I go about averaging MIN and MAX?
This is the query I am using:
$query = $pdo->prepare("SELECT AVG(bid),MIN(bid),MAX(bid) FROM bidding WHERE bid_id=:bid_id GROUP BY bid_id");
Try the following query to accomplish task
SELECT ((max(bid)+min(bid))/2) as average FROM bidding WHERE bid_id=:bid_id GROUP BY bid_id
Because the predefined avg function takes only one argument that may be column from table or single value. So you have to find the average of the min and max value of bid like above
As You are saying you need to find out the Min of Avg and Max of Avg,
Now what you are doing is group on one column this means Avg(Bid) will return only one value. And the thing that you are doing will make sense only if it is done with two column,
For example you wanna know the min of Averages per day. You need to identify one more column on which base you want to find out max and min of Avg. See in my example i am using Date as second column. the query will go like.
Select Max(MAx_Bid),Min(Min_Bid),Min(Avg_Bid),Max(Avg_Bid) FROM
(SELECT AVG(bid) Avg_Bid,MIN(bid) Mix_Bid,MAX(bid) max_bid FROM bidding WHERE bid_id=:bid_id GROUP BY bid_id,Days_Date(Dummy column))A